home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_1135 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  7.6 KB  |  234 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL 3'
  5. __copyright__ = '2010, Li Fanxi <lifanxi@freemindworld.com>'
  6. __docformat__ = 'restructuredtext en'
  7. import os
  8. import re
  9. from lxml import etree
  10. from calibre.ebooks.oeb.base import XHTML, XHTML_NS, barename, namespace
  11. from calibre.ebooks.oeb.stylizer import Stylizer
  12.  
  13. def ProcessFileName(fileName):
  14.     fileName = fileName.replace('/', '_').replace(os.sep, '_')
  15.     fileName = fileName.replace('#', '_')
  16.     fileName = fileName.lower()
  17.     (root, ext) = os.path.splitext(fileName)
  18.     if ext in ('.jpeg', '.jpg', '.gif', '.svg', '.png'):
  19.         fileName = root + '.jpg'
  20.     
  21.     return fileName
  22.  
  23. BLOCK_TAGS = [
  24.     'div',
  25.     'p',
  26.     'h1',
  27.     'h2',
  28.     'h3',
  29.     'h4',
  30.     'h5',
  31.     'h6',
  32.     'li',
  33.     'tr']
  34. BLOCK_STYLES = [
  35.     'block']
  36. SPACE_TAGS = [
  37.     'td']
  38. CALIBRE_SNB_IMG_TAG = '<$$calibre_snb_temp_img$$>'
  39. CALIBRE_SNB_BM_TAG = '<$$calibre_snb_bm_tag$$>'
  40. CALIBRE_SNB_PRE_TAG = '<$$calibre_snb_pre_tag$$>'
  41.  
  42. class SNBMLizer(object):
  43.     curSubItem = ''
  44.     
  45.     def __init__(self, log):
  46.         self.log = log
  47.  
  48.     
  49.     def extract_content(self, oeb_book, item, subitems, opts):
  50.         self.log.info('Converting XHTML to SNBC...')
  51.         self.oeb_book = oeb_book
  52.         self.opts = opts
  53.         self.item = item
  54.         self.subitems = subitems
  55.         return self.mlize()
  56.  
  57.     
  58.     def merge_content(self, old_tree, oeb_book, item, subitems, opts):
  59.         newTrees = self.extract_content(oeb_book, item, subitems, opts)
  60.         body = old_tree.find('.//body')
  61.         if body != None:
  62.             for subName in newTrees:
  63.                 newbody = newTrees[subName].find('.//body')
  64.                 for entity in newbody:
  65.                     body.append(entity)
  66.                 
  67.             
  68.         
  69.  
  70.     
  71.     def mlize(self):
  72.         output = [
  73.             u'']
  74.         stylizer = Stylizer(self.item.data, self.item.href, self.oeb_book, self.opts, self.opts.output_profile)
  75.         content = unicode(etree.tostring(self.item.data.find(XHTML('body')), encoding = unicode))
  76.         trees = { }
  77.         for subitem, subtitle in self.subitems:
  78.             snbcTree = etree.Element('snbc')
  79.             snbcHead = etree.SubElement(snbcTree, 'head')
  80.             etree.SubElement(snbcHead, 'title').text = subtitle
  81.             if self.opts and self.opts.snb_hide_chapter_name:
  82.                 etree.SubElement(snbcHead, 'hidetitle').text = u'true'
  83.             
  84.             etree.SubElement(snbcTree, 'body')
  85.             trees[subitem] = snbcTree
  86.         
  87.         output.append(u'%s%s\n\n' % (CALIBRE_SNB_BM_TAG, ''))
  88.         output += self.dump_text(self.subitems, etree.fromstring(content), stylizer)[0]
  89.         output = self.cleanup_text(u''.join(output))
  90.         subitem = ''
  91.         bodyTree = trees[subitem].find('.//body')
  92.         for line in output.splitlines():
  93.             if not line.find(CALIBRE_SNB_PRE_TAG) == 0:
  94.                 line = line.strip(u' \t\n\rπÇÇ')
  95.             else:
  96.                 etree.SubElement(bodyTree, 'text').text = etree.CDATA(line[len(CALIBRE_SNB_PRE_TAG):])
  97.             if len(line) != 0:
  98.                 if line.find(CALIBRE_SNB_IMG_TAG) == 0:
  99.                     prefix = ProcessFileName(os.path.dirname(self.item.href))
  100.                     if prefix != '':
  101.                         etree.SubElement(bodyTree, 'img').text = prefix + '_' + line[len(CALIBRE_SNB_IMG_TAG):]
  102.                     else:
  103.                         etree.SubElement(bodyTree, 'img').text = line[len(CALIBRE_SNB_IMG_TAG):]
  104.                 elif line.find(CALIBRE_SNB_BM_TAG) == 0:
  105.                     subitem = line[len(CALIBRE_SNB_BM_TAG):]
  106.                     bodyTree = trees[subitem].find('.//body')
  107.                 elif self.opts and self.opts.snb_indent_first_line:
  108.                     prefix = u'πÇÇπÇÇ'
  109.                 else:
  110.                     prefix = u''
  111.                 etree.SubElement(bodyTree, 'text').text = etree.CDATA(unicode(prefix + line))
  112.                 if self.opts and self.opts.snb_insert_empty_line:
  113.                     etree.SubElement(bodyTree, 'text').text = etree.CDATA(u'')
  114.                 
  115.             self.opts.snb_insert_empty_line
  116.         
  117.         return trees
  118.  
  119.     
  120.     def remove_newlines(self, text):
  121.         self.log.debug('\tRemove newlines for processing...')
  122.         text = text.replace('\r\n', ' ')
  123.         text = text.replace('\n', ' ')
  124.         text = text.replace('\r', ' ')
  125.         return text
  126.  
  127.     
  128.     def cleanup_text(self, text):
  129.         self.log.debug('\tClean up text...')
  130.         text = text.replace(u'├é', '')
  131.         text = text.replace(u'┬á', ' ')
  132.         text = text.replace(u'┬⌐', '(C)')
  133.         text = text.replace('\t+', ' ')
  134.         text = text.replace('\x0b+', ' ')
  135.         text = text.replace('\x0c+', ' ')
  136.         text = re.sub('(?<=.)%s(?=.)' % os.linesep, ' ', text)
  137.         text = re.sub('\n[ ]+\n', '\n\n', text)
  138.         if self.opts.remove_paragraph_spacing:
  139.             text = re.sub('\n{2,}', '\n', text)
  140.             text = re.sub('(?imu)^(?=.)', '\t', text)
  141.         else:
  142.             text = re.sub('\n{3,}', '\n\n', text)
  143.         text = re.sub('(?imu)^[ ]+', '', text)
  144.         text = re.sub('(?imu)[ ]+$', '', text)
  145.         if self.opts.snb_max_line_length:
  146.             max_length = self.opts.snb_max_line_length
  147.             if self.opts.max_line_length < 25:
  148.                 max_length = 25
  149.             
  150.             short_lines = []
  151.             lines = text.splitlines()
  152.             for line in lines:
  153.                 while len(line) > max_length:
  154.                     space = line.rfind(' ', 0, max_length)
  155.                     if space != -1:
  156.                         short_lines.append(line[:space])
  157.                         line = line[space + 1:]
  158.                         continue
  159.                     if False and self.opts.force_max_line_length:
  160.                         short_lines.append(line[:max_length])
  161.                         line = line[max_length:]
  162.                         continue
  163.                     space = line.find(' ', max_length, len(line))
  164.                     if space != -1:
  165.                         short_lines.append(line[:space])
  166.                         line = line[space + 1:]
  167.                         continue
  168.                     short_lines.append(line)
  169.                     line = ''
  170.                 short_lines.append(line)
  171.             
  172.             text = '\n'.join(short_lines)
  173.         
  174.         return text
  175.  
  176.     
  177.     def dump_text(self, subitems, elem, stylizer, end = '', pre = False, li = ''):
  178.         if not isinstance(elem.tag, basestring) or namespace(elem.tag) != XHTML_NS:
  179.             return [
  180.                 '']
  181.         text = [
  182.             '']
  183.         style = stylizer.style(elem)
  184.         if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') or style['visibility'] == 'hidden':
  185.             return [
  186.                 '']
  187.         tag = barename(elem.tag)
  188.         in_block = False
  189.         if tag in SPACE_TAGS:
  190.             if not end.endswith('u ') and hasattr(elem, 'text') and elem.text:
  191.                 text.append(u' ')
  192.             
  193.         
  194.         if tag == 'img':
  195.             text.append(u'\n\n%s%s\n\n' % (CALIBRE_SNB_IMG_TAG, ProcessFileName(elem.attrib['src'])))
  196.         
  197.         if tag == 'br':
  198.             text.append(u'\n\n')
  199.         
  200.         if tag == 'li':
  201.             li = '- '
  202.         
  203.         if not tag == 'pre':
  204.             pass
  205.         pre = pre
  206.         if hasattr(elem, 'text') and elem.text:
  207.             if pre:
  208.                 text.append((u'\n\n%s' % CALIBRE_SNB_PRE_TAG).join((li + elem.text).splitlines()))
  209.             else:
  210.                 text.append(li + elem.text)
  211.             li = ''
  212.         
  213.         for item in elem:
  214.             en = u''
  215.             if len(text) >= 2:
  216.                 en = text[-1][-2:]
  217.             
  218.             t = self.dump_text(subitems, item, stylizer, en, pre, li)[0]
  219.             text += t
  220.         
  221.         if in_block:
  222.             text.append(u'\n\n')
  223.         
  224.         if hasattr(elem, 'tail') and elem.tail:
  225.             if pre:
  226.                 text.append((u'\n\n%s' % CALIBRE_SNB_PRE_TAG).join(elem.tail.splitlines()))
  227.             else:
  228.                 text.append(li + elem.tail)
  229.             li = ''
  230.         
  231.         return (text, li)
  232.  
  233.  
  234.