home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_873 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  9.8 KB  |  245 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. __license__ = 'GPL 3'
  6. __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
  7. __docformat__ = 'restructuredtext en'
  8. import sys
  9. import os
  10. from optparse import OptionGroup, Option
  11. from calibre.utils.config import OptionParser
  12. from calibre.utils.logging import Log
  13. from calibre.constants import preferred_encoding
  14. from calibre.customize.conversion import OptionRecommendation
  15. from calibre import patheq
  16. USAGE = '%prog ' + _('input_file output_file [options]\n\nConvert an ebook from one format to another.\n\ninput_file is the input and output_file is the output. Both must be specified as the first two arguments to the command.\n\nThe output ebook format is guessed from the file extension of output_file. output_file can also be of the special format .EXT where EXT is the output file extension. In this case, the name of the output file is derived the name of the input file. Note that the filenames must not start with a hyphen. Finally, if output_file has no extension, then it is treated as a directory and an "open ebook" (OEB) consisting of HTML files is written to that directory. These files are the files that would normally have been passed to the output plugin.\n\nAfter specifying the input and output file you can customize the conversion by specifying various options. The available options depend on the input and output file types. To get help on them specify the input and output file and then use the -h option.\n\nFor full documentation of the conversion system see\n') + 'http://calibre-ebook.com/user_manual/conversion.html'
  17.  
  18. def print_help(parser, log):
  19.     help = parser.format_help().encode(preferred_encoding, 'replace')
  20.     log(help)
  21.  
  22.  
  23. def check_command_line_options(parser, args, log):
  24.     if len(args) < 3 and args[1].startswith('-') or args[2].startswith('-'):
  25.         print_help(parser, log)
  26.         log.error('\n\nYou must specify the input AND output files')
  27.         raise SystemExit(1)
  28.     args[2].startswith('-')
  29.     input = os.path.abspath(args[1])
  30.     if not input.endswith('.recipe') and not os.access(input, os.R_OK):
  31.         if not '-h' in args:
  32.             pass
  33.         if not ('--help' in args):
  34.             log.error('Cannot read from', input)
  35.             raise SystemExit(1)
  36.     not ('--help' in args)
  37.     output = args[2]
  38.     if output.startswith('.') and output != '.':
  39.         output = os.path.splitext(os.path.basename(input))[0] + output
  40.     
  41.     output = os.path.abspath(output)
  42.     return (input, output)
  43.  
  44.  
  45. def option_recommendation_to_cli_option(add_option, rec):
  46.     opt = rec.option
  47.     switches = None if opt.short_switch else []
  48.     switches.append('--' + opt.long_switch)
  49.     attrs = dict(dest = opt.name, help = opt.help, choices = opt.choices, default = rec.recommended_value)
  50.     if isinstance(rec.recommended_value, type(True)):
  51.         attrs['action'] = None if rec.recommended_value else 'store_true'
  52.     elif isinstance(rec.recommended_value, int):
  53.         attrs['type'] = 'int'
  54.     
  55.     if isinstance(rec.recommended_value, float):
  56.         attrs['type'] = 'float'
  57.     
  58.     if opt.long_switch == 'verbose':
  59.         attrs['action'] = 'count'
  60.         attrs.pop('type', '')
  61.     
  62.     add_option(Option(*switches, **attrs))
  63.  
  64.  
  65. def add_input_output_options(parser, plumber):
  66.     input_options = plumber.input_options
  67.     output_options = plumber.output_options
  68.     
  69.     def add_options(group, options):
  70.         for opt in options:
  71.             option_recommendation_to_cli_option(group, opt)
  72.         
  73.  
  74.     if input_options:
  75.         title = _('INPUT OPTIONS')
  76.         io = OptionGroup(parser, title, _('Options to control the processing of the input %s file') % plumber.input_fmt)
  77.         add_options(io.add_option, input_options)
  78.         parser.add_option_group(io)
  79.     
  80.     if output_options:
  81.         title = _('OUTPUT OPTIONS')
  82.         oo = OptionGroup(parser, title, _('Options to control the processing of the output %s') % plumber.output_fmt)
  83.         add_options(oo.add_option, output_options)
  84.         parser.add_option_group(oo)
  85.     
  86.  
  87.  
  88. def add_pipeline_options(parser, plumber):
  89.     groups = {
  90.         '': ('', [
  91.             'input_profile',
  92.             'output_profile']),
  93.         'LOOK AND FEEL': (_('Options to control the look and feel of the output'), [
  94.             'base_font_size',
  95.             'disable_font_rescaling',
  96.             'font_size_mapping',
  97.             'line_height',
  98.             'linearize_tables',
  99.             'extra_css',
  100.             'margin_top',
  101.             'margin_left',
  102.             'margin_right',
  103.             'margin_bottom',
  104.             'change_justification',
  105.             'insert_blank_line',
  106.             'remove_paragraph_spacing',
  107.             'remove_paragraph_spacing_indent_size',
  108.             'asciiize',
  109.             'remove_header',
  110.             'header_regex',
  111.             'remove_footer',
  112.             'footer_regex']),
  113.         'STRUCTURE DETECTION': (_('Control auto-detection of document structure.'), [
  114.             'chapter',
  115.             'chapter_mark',
  116.             'prefer_metadata_cover',
  117.             'remove_first_image',
  118.             'insert_metadata',
  119.             'page_breaks_before',
  120.             'preprocess_html']),
  121.         'TABLE OF CONTENTS': (_('Control the automatic generation of a Table of Contents. By default, if the source file has a Table of Contents, it will be used in preference to the automatically generated one.'), [
  122.             'level1_toc',
  123.             'level2_toc',
  124.             'level3_toc',
  125.             'toc_threshold',
  126.             'max_toc_links',
  127.             'no_chapters_in_toc',
  128.             'use_auto_toc',
  129.             'toc_filter']),
  130.         'METADATA': (_('Options to set metadata in the output'), plumber.metadata_option_names),
  131.         'DEBUG': (_('Options to help with debugging the conversion'), [
  132.             'verbose',
  133.             'debug_pipeline']) }
  134.     group_order = [
  135.         '',
  136.         'LOOK AND FEEL',
  137.         'STRUCTURE DETECTION',
  138.         'TABLE OF CONTENTS',
  139.         'METADATA',
  140.         'DEBUG']
  141.     for group in group_order:
  142.         (desc, options) = groups[group]
  143.         if group:
  144.             group = OptionGroup(parser, group, desc)
  145.             parser.add_option_group(group)
  146.         
  147.         add_option = None if group != '' else parser.add_option
  148.         for name in options:
  149.             rec = plumber.get_option_by_name(name)
  150.             if rec.level < rec.HIGH:
  151.                 option_recommendation_to_cli_option(add_option, rec)
  152.                 continue
  153.         
  154.     
  155.     parser.add_option('--list-recipes', default = False, action = 'store_true', help = _('List builtin recipes'))
  156.  
  157.  
  158. def option_parser():
  159.     return OptionParser(usage = USAGE)
  160.  
  161.  
  162. class ProgressBar(object):
  163.     
  164.     def __init__(self, log):
  165.         self.log = log
  166.  
  167.     
  168.     def __call__(self, frac, msg = ''):
  169.         if msg:
  170.             percent = int(frac * 100)
  171.             self.log('%d%% %s' % (percent, msg))
  172.         
  173.  
  174.  
  175.  
  176. def create_option_parser(args, log):
  177.     if '--version' in args:
  178.         __appname__ = __appname__
  179.         __version__ = __version__
  180.         __author__ = __author__
  181.         import calibre.constants
  182.         log(os.path.basename(args[0]), '(' + __appname__, __version__ + ')')
  183.         log('Created by:', __author__)
  184.         raise SystemExit(0)
  185.     '--version' in args
  186.     if '--list-recipes' in args:
  187.         get_builtin_recipe_titles = get_builtin_recipe_titles
  188.         import calibre.web.feeds.recipes.collection
  189.         log('Available recipes:')
  190.         titles = sorted(get_builtin_recipe_titles())
  191.         for title in titles:
  192.             
  193.             try:
  194.                 log('\t' + title)
  195.             continue
  196.             log('\t' + repr(title))
  197.             continue
  198.  
  199.         
  200.         log('%d recipes available' % len(titles))
  201.         raise SystemExit(0)
  202.     '--list-recipes' in args
  203.     parser = option_parser()
  204.     if len(args) < 3:
  205.         print_help(parser, log)
  206.         raise SystemExit(1)
  207.     len(args) < 3
  208.     (input, output) = check_command_line_options(parser, args, log)
  209.     Plumber = Plumber
  210.     import calibre.ebooks.conversion.plumber
  211.     reporter = ProgressBar(log)
  212.     if patheq(input, output):
  213.         raise ValueError('Input file is the same as the output file')
  214.     patheq(input, output)
  215.     plumber = Plumber(input, output, log, reporter)
  216.     add_input_output_options(parser, plumber)
  217.     add_pipeline_options(parser, plumber)
  218.     return (parser, plumber)
  219.  
  220.  
  221. def abspath(x):
  222.     if x.startswith('http:') or x.startswith('https:'):
  223.         return x
  224.     return os.path.abspath(os.path.expanduser(x))
  225.  
  226.  
  227. def main(args = sys.argv):
  228.     log = Log()
  229.     (parser, plumber) = create_option_parser(args, log)
  230.     opts = parser.parse_args(args)[0]
  231.     for x in ('read_metadata_from_opf', 'cover'):
  232.         if getattr(opts, x, None) is not None:
  233.             setattr(opts, x, abspath(getattr(opts, x)))
  234.             continue
  235.     
  236.     recommendations = _[1]
  237.     plumber.merge_ui_recommendations(recommendations)
  238.     plumber.run()
  239.     log(_('Output saved to'), ' ', plumber.output)
  240.     return 0
  241.  
  242. if __name__ == '__main__':
  243.     sys.exit(main())
  244.  
  245.