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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
  6. __docformat__ = 'restructuredtext en'
  7. import os
  8. import mimetypes
  9. import sys
  10. import re
  11. from urllib import unquote, quote
  12. from urlparse import urlparse
  13. from calibre import relpath
  14. from calibre.utils.config import tweaks
  15. _author_pat = re.compile(',?\\s+(and|with)\\s+', re.IGNORECASE)
  16.  
  17. def string_to_authors(raw):
  18.     raw = raw.replace('&&', u'∩┐┐')
  19.     raw = _author_pat.sub('&', raw)
  20.     authors = [ a.strip().replace(u'∩┐┐', '&') for a in raw.split('&') ]
  21.     return _[2]
  22.  
  23.  
  24. def authors_to_string(authors):
  25.     if authors is not None:
  26.         return [](_[1])
  27.     return ''
  28.  
  29. _bracket_pat = re.compile('[\\[({].*?[})\\]]')
  30.  
  31. def author_to_author_sort(author):
  32.     if not author:
  33.         return ''
  34.     method = tweaks['author_sort_copy_method']
  35.     if (method == 'copy' or method == 'comma') and ',' in author:
  36.         return author
  37.     author = _bracket_pat.sub('', author).strip()
  38.     tokens = author.split()
  39.     tokens = tokens[-1:] + tokens[:-1]
  40.     return ' '.join(tokens)
  41.  
  42.  
  43. def authors_to_sort_string(authors):
  44.     return ' & '.join(map(author_to_author_sort, authors))
  45.  
  46.  
  47. try:
  48.     _title_pat = re.compile(tweaks.get('title_sort_articles', '^(A|The|An)\\s+'), re.IGNORECASE)
  49. except:
  50.     print 'Error in title sort pattern'
  51.     import traceback
  52.     traceback.print_exc()
  53.     _title_pat = re.compile('^(A|The|An)\\s+', re.IGNORECASE)
  54.  
  55. _ignore_starts = u'\'"' + u''.join((lambda .0: for x in .0:
  56. unichr(x))(range(8216, 8222) + [
  57.     8242,
  58.     8243]))
  59.  
  60. def title_sort(title):
  61.     title = title.strip()
  62.     if title and title[0] in _ignore_starts:
  63.         title = title[1:]
  64.     
  65.     match = _title_pat.search(title)
  66.     if match:
  67.         prep = match.group(1)
  68.         title = title[len(prep):] + ', ' + prep
  69.     
  70.     return title.strip()
  71.  
  72. coding = zip([
  73.     1000,
  74.     900,
  75.     500,
  76.     400,
  77.     100,
  78.     90,
  79.     50,
  80.     40,
  81.     10,
  82.     9,
  83.     5,
  84.     4,
  85.     1], [
  86.     'M',
  87.     'CM',
  88.     'D',
  89.     'CD',
  90.     'C',
  91.     'XC',
  92.     'L',
  93.     'XL',
  94.     'X',
  95.     'IX',
  96.     'V',
  97.     'IV',
  98.     'I'])
  99.  
  100. def roman(num):
  101.     if num <= 0 and num >= 4000 or int(num) != num:
  102.         return str(num)
  103.     result = []
  104.     for d, r in coding:
  105.         while num >= d:
  106.             result.append(r)
  107.             num -= d
  108.             continue
  109.             int(num) != num
  110.     
  111.     return ''.join(result)
  112.  
  113.  
  114. def fmt_sidx(i, fmt = '%.2f', use_roman = False):
  115.     if i is None or i == '':
  116.         i = 1
  117.     
  118.     
  119.     try:
  120.         i = float(i)
  121.     except TypeError:
  122.         return str(i)
  123.  
  124.     if int(i) == float(i):
  125.         if use_roman:
  126.             return roman(int(i))
  127.         return '%d' % int(i)
  128.     return fmt % i
  129.  
  130.  
  131. class Resource(object):
  132.     
  133.     def __init__(self, href_or_path, basedir = os.getcwd(), is_path = True):
  134.         self._href = None
  135.         self._basedir = basedir
  136.         self.path = None
  137.         self.fragment = ''
  138.         
  139.         try:
  140.             self.mime_type = mimetypes.guess_type(href_or_path)[0]
  141.         except:
  142.             self.mime_type = None
  143.  
  144.         if self.mime_type is None:
  145.             self.mime_type = 'application/octet-stream'
  146.         
  147.         if is_path:
  148.             path = href_or_path
  149.             if not os.path.isabs(path):
  150.                 path = os.path.abspath(os.path.join(basedir, path))
  151.             
  152.             if isinstance(path, str):
  153.                 path = path.decode(sys.getfilesystemencoding())
  154.             
  155.             self.path = path
  156.         else:
  157.             url = urlparse(href_or_path)
  158.             if url[0] not in ('', 'file'):
  159.                 self._href = href_or_path
  160.             else:
  161.                 pc = url[2]
  162.                 if isinstance(pc, unicode):
  163.                     pc = pc.encode('utf-8')
  164.                 
  165.                 pc = unquote(pc).decode('utf-8')
  166.                 self.path = os.path.abspath(os.path.join(basedir, pc.replace('/', os.sep)))
  167.                 self.fragment = unquote(url[-1])
  168.  
  169.     
  170.     def href(self, basedir = None):
  171.         if basedir is None:
  172.             if self._basedir:
  173.                 basedir = self._basedir
  174.             else:
  175.                 basedir = os.getcwd()
  176.         
  177.         if self.path is None:
  178.             return self._href
  179.         f = self.path is None if isinstance(self.fragment, unicode) else self.fragment
  180.         frag = None if self.fragment else ''
  181.         if self.path == basedir:
  182.             return '' + frag
  183.         
  184.         try:
  185.             rpath = relpath(self.path, basedir)
  186.         except OSError:
  187.             self.path == basedir
  188.             self.path == basedir
  189.             rpath = self.path
  190.         except:
  191.             self.path == basedir
  192.  
  193.         if isinstance(rpath, unicode):
  194.             rpath = rpath.encode('utf-8')
  195.         
  196.         return quote(rpath.replace(os.sep, '/')) + frag
  197.  
  198.     
  199.     def set_basedir(self, path):
  200.         self._basedir = path
  201.  
  202.     
  203.     def basedir(self):
  204.         return self._basedir
  205.  
  206.     
  207.     def __repr__(self):
  208.         return 'Resource(%s, %s)' % (repr(self.path), repr(self.href()))
  209.  
  210.  
  211.  
  212. class ResourceCollection(object):
  213.     
  214.     def __init__(self):
  215.         self._resources = []
  216.  
  217.     
  218.     def __iter__(self):
  219.         for r in self._resources:
  220.             yield r
  221.         
  222.  
  223.     
  224.     def __len__(self):
  225.         return len(self._resources)
  226.  
  227.     
  228.     def __getitem__(self, index):
  229.         return self._resources[index]
  230.  
  231.     
  232.     def __bool__(self):
  233.         return len(self._resources) > 0
  234.  
  235.     
  236.     def __str__(self):
  237.         resources = map(repr, self)
  238.         return '[%s]' % ', '.join(resources)
  239.  
  240.     
  241.     def __repr__(self):
  242.         return str(self)
  243.  
  244.     
  245.     def append(self, resource):
  246.         if not isinstance(resource, Resource):
  247.             raise ValueError('Can only append objects of type Resource')
  248.         isinstance(resource, Resource)
  249.         self._resources.append(resource)
  250.  
  251.     
  252.     def remove(self, resource):
  253.         self._resources.remove(resource)
  254.  
  255.     
  256.     def replace(self, start, end, items):
  257.         self._resources[start:end] = items
  258.  
  259.     
  260.     def from_directory_contents(top, topdown = True):
  261.         collection = ResourceCollection()
  262.         for spec in os.walk(top, topdown = topdown):
  263.             path = os.path.abspath(os.path.join(spec[0], spec[1]))
  264.             res = Resource.from_path(path)
  265.             res.set_basedir(top)
  266.             collection.append(res)
  267.         
  268.         return collection
  269.  
  270.     from_directory_contents = staticmethod(from_directory_contents)
  271.     
  272.     def set_basedir(self, path):
  273.         for res in self:
  274.             res.set_basedir(path)
  275.         
  276.  
  277.  
  278.  
  279. def MetaInformation(title, authors = (_('Unknown'),)):
  280.     Metadata = Metadata
  281.     import calibre.ebooks.metadata.book.base
  282.     mi = None
  283.     if hasattr(title, 'title') and hasattr(title, 'authors'):
  284.         mi = title
  285.         title = mi.title
  286.         authors = mi.authors
  287.     
  288.     return Metadata(title, authors, other = mi)
  289.  
  290.  
  291. def check_isbn10(isbn):
  292.     
  293.     try:
  294.         digits = map(int, isbn[:9])
  295.         products = [ (i + 1) * digits[i] for i in range(9) ]
  296.         check = sum(products) % 11
  297.         if check == 10 or isbn[9] == 'X' or check == int(isbn[9]):
  298.             return isbn
  299.     except:
  300.         pass
  301.  
  302.  
  303.  
  304. def check_isbn13(isbn):
  305.     
  306.     try:
  307.         digits = map(int, isbn[:12])
  308.         products = [ _[1] if i % 2 == 0 else 3 * digits[i] for i in range(12) ]
  309.         check = 10 - sum(products) % 10
  310.         if check == 10:
  311.             check = 0
  312.         
  313.         if str(check) == isbn[12]:
  314.             return isbn
  315.     except:
  316.         pass
  317.  
  318.  
  319.  
  320. def check_isbn(isbn):
  321.     isbn = re.sub('[^0-9X]', '', isbn.upper())
  322.     if len(isbn) == 10:
  323.         return check_isbn10(isbn)
  324.     if len(isbn) == 13:
  325.         return check_isbn13(isbn)
  326.  
  327.