rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if hundredsComponent and tensComponent:
elif hundredsComponent and tensComponent:
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
else: prints(" NumberToText.stringFromInt(): empty result translating %d" % intToTranslate)
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
if self.verbose:
if False and self.verbose:
def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database
rules.insert(0
rules.insert(0,
def __call__(self, html, remove_special_chars=None): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif self.is_pdftohtml(html): rules = self.PDFTOHTML else: rules = []
w += '="%s%%"' % width
w += '="%s"' % width
def dump_text(self, elem, stylizer, page, tag_stack=[]): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return []
rpages = []
pagelist_template = u'''\ <div class="pagelist"> <ul> {pages} </ul> </div> ''' rpages, lpages = [], []
def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/browse/booklist_page"></span> <span class="start" title="{start}"></span> <span class="end" title="{end}"></span> </div> <div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div> <div class="loaded"></div> </div> ''' rpages = [] for i, x in enumerate(pages): pg, pos = x ld = xml(json.dumps(pg), True) rpages.append(page_template.format(i, ld, xml(_('Loading, please wait')) + '&hellip;', start=pos+1, end=pos+len(pg), prefix=prefix)) rpages = u'\n\n'.join(rpages) templ = u'''\ <h3>{0} {suffix}</h3> <div id="booklist"> <div class="listnav topnav"> {navbar} </div> {pages} <div class="listnav bottomnav"> {navbar} </div> </div> ''' navbar = u'''\ <div class="navleft"> <a href="#" onclick="first_page(); return false;">{first}</a> <a href="#" onclick="previous_page(); return false;">{previous}</a> </div> <div class="navmiddle"> <span class="start">0</span> to <span class="end">0</span> of {num} </div> <div class="navright"> <a href="#" onclick="next_page(); return false;">{next}</a> <a href="#" onclick="last_page(); return false;">{last}</a> </div> '''.format(first=_('First'), last=_('Last'), previous=_('Previous'), next=_('Next'), num=num) return templ.format(_('Browsing %d books')%num, suffix=suffix, pages=rpages, navbar=navbar)
start=pos+1, end=pos+len(pg), prefix=prefix))
start=start, end=end, prefix=prefix)) lpages.append(' '*20 + (u'<li><a href=" ' onclick="gp_internal(\'{id}\'); return false;"> ' '{start}&nbsp;to&nbsp;{end}</a></li>').format(start=start, end=end, id='page%d'%i))
def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/browse/booklist_page"></span> <span class="start" title="{start}"></span> <span class="end" title="{end}"></span> </div> <div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div> <div class="loaded"></div> </div> ''' rpages = [] for i, x in enumerate(pages): pg, pos = x ld = xml(json.dumps(pg), True) rpages.append(page_template.format(i, ld, xml(_('Loading, please wait')) + '&hellip;', start=pos+1, end=pos+len(pg), prefix=prefix)) rpages = u'\n\n'.join(rpages) templ = u'''\ <h3>{0} {suffix}</h3> <div id="booklist"> <div class="listnav topnav"> {navbar} </div> {pages} <div class="listnav bottomnav"> {navbar} </div> </div> ''' navbar = u'''\ <div class="navleft"> <a href="#" onclick="first_page(); return false;">{first}</a> <a href="#" onclick="previous_page(); return false;">{previous}</a> </div> <div class="navmiddle"> <span class="start">0</span> to <span class="end">0</span> of {num} </div> <div class="navright"> <a href="#" onclick="next_page(); return false;">{next}</a> <a href="#" onclick="last_page(); return false;">{last}</a> </div> '''.format(first=_('First'), last=_('Last'), previous=_('Previous'), next=_('Next'), num=num) return templ.format(_('Browsing %d books')%num, suffix=suffix, pages=rpages, navbar=navbar)
gp_start = gp_end = '' if len(pages) > 1: gp_start = '<a href=" (_('Go to') + '&hellip;') gp_end = '</a>'
def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/browse/booklist_page"></span> <span class="start" title="{start}"></span> <span class="end" title="{end}"></span> </div> <div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div> <div class="loaded"></div> </div> ''' rpages = [] for i, x in enumerate(pages): pg, pos = x ld = xml(json.dumps(pg), True) rpages.append(page_template.format(i, ld, xml(_('Loading, please wait')) + '&hellip;', start=pos+1, end=pos+len(pg), prefix=prefix)) rpages = u'\n\n'.join(rpages) templ = u'''\ <h3>{0} {suffix}</h3> <div id="booklist"> <div class="listnav topnav"> {navbar} </div> {pages} <div class="listnav bottomnav"> {navbar} </div> </div> ''' navbar = u'''\ <div class="navleft"> <a href="#" onclick="first_page(); return false;">{first}</a> <a href="#" onclick="previous_page(); return false;">{previous}</a> </div> <div class="navmiddle"> <span class="start">0</span> to <span class="end">0</span> of {num} </div> <div class="navright"> <a href="#" onclick="next_page(); return false;">{next}</a> <a href="#" onclick="last_page(); return false;">{last}</a> </div> '''.format(first=_('First'), last=_('Last'), previous=_('Previous'), next=_('Next'), num=num) return templ.format(_('Browsing %d books')%num, suffix=suffix, pages=rpages, navbar=navbar)
<span class="start">0</span> to <span class="end">0</span> of {num}
{gp_start} <span class="start">0</span> to <span class="end">0</span> {gp_end}of {num}
def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/browse/booklist_page"></span> <span class="start" title="{start}"></span> <span class="end" title="{end}"></span> </div> <div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div> <div class="loaded"></div> </div> ''' rpages = [] for i, x in enumerate(pages): pg, pos = x ld = xml(json.dumps(pg), True) rpages.append(page_template.format(i, ld, xml(_('Loading, please wait')) + '&hellip;', start=pos+1, end=pos+len(pg), prefix=prefix)) rpages = u'\n\n'.join(rpages) templ = u'''\ <h3>{0} {suffix}</h3> <div id="booklist"> <div class="listnav topnav"> {navbar} </div> {pages} <div class="listnav bottomnav"> {navbar} </div> </div> ''' navbar = u'''\ <div class="navleft"> <a href="#" onclick="first_page(); return false;">{first}</a> <a href="#" onclick="previous_page(); return false;">{previous}</a> </div> <div class="navmiddle"> <span class="start">0</span> to <span class="end">0</span> of {num} </div> <div class="navright"> <a href="#" onclick="next_page(); return false;">{next}</a> <a href="#" onclick="last_page(); return false;">{last}</a> </div> '''.format(first=_('First'), last=_('Last'), previous=_('Previous'), next=_('Next'), num=num) return templ.format(_('Browsing %d books')%num, suffix=suffix, pages=rpages, navbar=navbar)
next=_('Next'), num=num)
next=_('Next'), num=num, gp_start=gp_start, gp_end=gp_end)
def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/browse/booklist_page"></span> <span class="start" title="{start}"></span> <span class="end" title="{end}"></span> </div> <div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div> <div class="loaded"></div> </div> ''' rpages = [] for i, x in enumerate(pages): pg, pos = x ld = xml(json.dumps(pg), True) rpages.append(page_template.format(i, ld, xml(_('Loading, please wait')) + '&hellip;', start=pos+1, end=pos+len(pg), prefix=prefix)) rpages = u'\n\n'.join(rpages) templ = u'''\ <h3>{0} {suffix}</h3> <div id="booklist"> <div class="listnav topnav"> {navbar} </div> {pages} <div class="listnav bottomnav"> {navbar} </div> </div> ''' navbar = u'''\ <div class="navleft"> <a href="#" onclick="first_page(); return false;">{first}</a> <a href="#" onclick="previous_page(); return false;">{previous}</a> </div> <div class="navmiddle"> <span class="start">0</span> to <span class="end">0</span> of {num} </div> <div class="navright"> <a href="#" onclick="next_page(); return false;">{next}</a> <a href="#" onclick="last_page(); return false;">{last}</a> </div> '''.format(first=_('First'), last=_('Last'), previous=_('Previous'), next=_('Next'), num=num) return templ.format(_('Browsing %d books')%num, suffix=suffix, pages=rpages, navbar=navbar)
pages=rpages, navbar=navbar)
pages=rpages, navbar=navbar, pagelist=pagelist, goto=xml(_('Go to'), True) + '&hellip;')
def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/browse/booklist_page"></span> <span class="start" title="{start}"></span> <span class="end" title="{end}"></span> </div> <div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div> <div class="loaded"></div> </div> ''' rpages = [] for i, x in enumerate(pages): pg, pos = x ld = xml(json.dumps(pg), True) rpages.append(page_template.format(i, ld, xml(_('Loading, please wait')) + '&hellip;', start=pos+1, end=pos+len(pg), prefix=prefix)) rpages = u'\n\n'.join(rpages) templ = u'''\ <h3>{0} {suffix}</h3> <div id="booklist"> <div class="listnav topnav"> {navbar} </div> {pages} <div class="listnav bottomnav"> {navbar} </div> </div> ''' navbar = u'''\ <div class="navleft"> <a href="#" onclick="first_page(); return false;">{first}</a> <a href="#" onclick="previous_page(); return false;">{previous}</a> </div> <div class="navmiddle"> <span class="start">0</span> to <span class="end">0</span> of {num} </div> <div class="navright"> <a href="#" onclick="next_page(); return false;">{next}</a> <a href="#" onclick="last_page(); return false;">{last}</a> </div> '''.format(first=_('First'), last=_('Last'), previous=_('Previous'), next=_('Next'), num=num) return templ.format(_('Browsing %d books')%num, suffix=suffix, pages=rpages, navbar=navbar)
try: self.root = os.getcwdu() except: pass
def __init__(self, stream, mode='r', root=None): try: self.archive = ZipFile(stream, mode=mode) except BadZipfile: raise EPubException("not a ZIP .epub OCF container") self.root = root if self.root is None: try: self.root = os.getcwdu() except: pass if hasattr(stream, 'name'): self.root = os.path.abspath(os.path.dirname(stream.name)) super(OCFZipReader, self).__init__()
if self.series.currentIndex() > -1: mi.series = unicode(self.series.currentText()).strip()
series = unicode(self.series.currentText()).strip() if series: mi.series = series
def get_metadata(self): title, authors = self.get_title_and_authors() mi = MetaInformation(title, authors) publisher = unicode(self.publisher.text()).strip() if publisher: mi.publisher = publisher author_sort = unicode(self.author_sort.text()).strip() if author_sort: mi.author_sort = author_sort comments = unicode(self.comment.toPlainText()).strip() if comments: mi.comments = comments mi.series_index = float(self.series_index.value()) if self.series.currentIndex() > -1: mi.series = unicode(self.series.currentText()).strip() tags = [t.strip() for t in unicode(self.tags.text()).strip().split(',')] if tags: mi.tags = tags
def create_exth(self, exth=None):
def create_exth(self, new_title=None, exth=None):
def create_exth(self, exth=None): # Add an EXTH block to record 0, rewrite the stream # self.hexdump(self.record0)
new_record0.write(title_in_file)
if new_title: new_title = (new_title or _('Unknown')).encode(self.codec, 'replace') new_record0.write(new_title) else: new_record0.write(title_in_file)
def create_exth(self, exth=None): # Add an EXTH block to record 0, rewrite the stream # self.hexdump(self.record0)
self.create_exth(exth)
self.create_exth(exth=exth, new_title=mi.title)
def update(self, mi): if self.type != "BOOKMOBI": raise MobiError("Setting metadata only supported for MOBI files of type 'BOOK'.\n" "\tThis is a '%s' file of type '%s'" % (self.type[0:4], self.type[4:8]))
d = error_dialog(self.window, _('Cannot read'),
d = error_dialog(self, _('Cannot read'),
def select_cover(self, checked): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.window, _('Cannot read'), _('You do not have permission to read the file: ') + _file) d.exec_() return cf, cover = None, None try: cf = open(_file, "rb") cover = cf.read() except IOError, e: d = error_dialog(self.window, _('Error reading file'), _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e)) d.exec_() if cover: pix = QPixmap() pix.loadFromData(cover) if pix.isNull(): d = error_dialog(self.window, _("Not a valid picture"), _file + _(" is not a valid picture")) d.exec_() else: self.cover_path.setText(_file) self.cover.setPixmap(pix) self.cover_changed = True self.cpixmap = pix self.cover_data = cover
d = error_dialog(self.window, _('Error reading file'),
d = error_dialog(self, _('Error reading file'),
def select_cover(self, checked): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.window, _('Cannot read'), _('You do not have permission to read the file: ') + _file) d.exec_() return cf, cover = None, None try: cf = open(_file, "rb") cover = cf.read() except IOError, e: d = error_dialog(self.window, _('Error reading file'), _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e)) d.exec_() if cover: pix = QPixmap() pix.loadFromData(cover) if pix.isNull(): d = error_dialog(self.window, _("Not a valid picture"), _file + _(" is not a valid picture")) d.exec_() else: self.cover_path.setText(_file) self.cover.setPixmap(pix) self.cover_changed = True self.cpixmap = pix self.cover_data = cover
d = error_dialog(self.window,
d = error_dialog(self,
def select_cover(self, checked): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.window, _('Cannot read'), _('You do not have permission to read the file: ') + _file) d.exec_() return cf, cover = None, None try: cf = open(_file, "rb") cover = cf.read() except IOError, e: d = error_dialog(self.window, _('Error reading file'), _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e)) d.exec_() if cover: pix = QPixmap() pix.loadFromData(cover) if pix.isNull(): d = error_dialog(self.window, _("Not a valid picture"), _file + _(" is not a valid picture")) d.exec_() else: self.cover_path.setText(_file) self.cover.setPixmap(pix) self.cover_changed = True self.cpixmap = pix self.cover_data = cover
error_dialog(self.window, _('No permission'),
error_dialog(self, _('No permission'),
def _add_formats(self, paths): added = False if not paths: return added bad_perms = [] for _file in paths: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): bad_perms.append(_file) continue
fromstring = functools.partial(etree.fromstring, parser=RECOVER_PARSER)
parser = etree.XMLParser(no_network=True, huge_tree=True)
def _parse_xhtml(self, data): self.oeb.log.debug('Parsing', self.href, '...') # Convert to Unicode and normalize line endings data = self.oeb.decode(data) data = self.oeb.html_preprocessor(data)
data = fromstring(data)
data = etree.fromstring(data, parser=parser)
def first_pass(data): try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.log.exception('Initial parse failed:') repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0)) data = ENTITY_RE.sub(repl, data) try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.logger.warn('Parsing file %r as HTML' % self.href) if err.args and err.args[0].startswith('Excessive depth'): from lxml.html import soupparser data = soupparser.fromstring(data) else: data = html.fromstring(data) data.attrib.pop('xmlns', None) for elem in data.iter(tag=etree.Comment): if elem.text: elem.text = elem.text.strip('-') data = etree.tostring(data, encoding=unicode) try: data = fromstring(data) except etree.XMLSyntaxError: data = fromstring(data) return data
data = fromstring(data)
data = etree.fromstring(data, parser=RECOVER_PARSER)
def first_pass(data): try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.log.exception('Initial parse failed:') repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0)) data = ENTITY_RE.sub(repl, data) try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.logger.warn('Parsing file %r as HTML' % self.href) if err.args and err.args[0].startswith('Excessive depth'): from lxml.html import soupparser data = soupparser.fromstring(data) else: data = html.fromstring(data) data.attrib.pop('xmlns', None) for elem in data.iter(tag=etree.Comment): if elem.text: elem.text = elem.text.strip('-') data = etree.tostring(data, encoding=unicode) try: data = fromstring(data) except etree.XMLSyntaxError: data = fromstring(data) return data
data = fromstring(data)
data = etree.fromstring(data)
def first_pass(data): try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.log.exception('Initial parse failed:') repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0)) data = ENTITY_RE.sub(repl, data) try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.logger.warn('Parsing file %r as HTML' % self.href) if err.args and err.args[0].startswith('Excessive depth'): from lxml.html import soupparser data = soupparser.fromstring(data) else: data = html.fromstring(data) data.attrib.pop('xmlns', None) for elem in data.iter(tag=etree.Comment): if elem.text: elem.text = elem.text.strip('-') data = etree.tostring(data, encoding=unicode) try: data = fromstring(data) except etree.XMLSyntaxError: data = fromstring(data) return data
self.applied_items.sort(key=lambda x:sort_key(self.all_items[x]))
self.applied_items.sort(key=lambda x:sort_key(self.all_items[x].name))
def apply_tags(self, node=None): if self.current_cat_name is None: return nodes = self.available_items_box.selectedItems() if node is None else [node] for node in nodes: index = self.all_items[node.data(Qt.UserRole).toPyObject()].index if index not in self.applied_items: self.applied_items.append(index) self.applied_items.sort(key=lambda x:sort_key(self.all_items[x])) self.display_filtered_categories(None)
self.author = author
self.book_author = author
def __call__(self, title, author, publisher, isbn, verbose, log=None, extra=None): self.worker = Thread(target=self._fetch) self.worker.daemon = True self.title = title self.verbose = verbose self.author = author self.publisher = publisher self.isbn = isbn self.log = log if log is not None else default_log self.extra = extra self.exception, self.tb, self.results = None, None, [] self.worker.start()
self.results = search(self.title, self.author, self.publisher,
self.results = search(self.title, self.book_author, self.publisher,
def fetch(self): from calibre.ebooks.metadata.google_books import search try: self.results = search(self.title, self.author, self.publisher, self.isbn, max_results=10, verbose=self.verbose) except Exception, e: self.exception = e self.tb = traceback.format_exc()
if self.author: args.extend(['--author', self.author])
if self.book_author: args.extend(['--author', self.book_author])
def fetch(self): if not self.site_customization: return from calibre.ebooks.metadata.isbndb import option_parser, create_books args = ['isbndb'] if self.isbn: args.extend(['--isbn', self.isbn]) else: if self.title: args.extend(['--title', self.title]) if self.author: args.extend(['--author', self.author]) if self.publisher: args.extend(['--publisher', self.publisher]) if self.verbose: args.extend(['--verbose']) args.append(self.site_customization) # IsbnDb key try: opts, args = option_parser().parse_args(args) self.results = create_books(opts, args) except Exception, e: self.exception = e self.tb = traceback.format_exc()
self.results = get_social_metadata(self.title, self.author,
self.results = get_social_metadata(self.title, self.book_author,
def fetch(self): if not self.isbn: return from calibre.ebooks.metadata.amazon import get_social_metadata try: self.results = get_social_metadata(self.title, self.author, self.publisher, self.isbn) except Exception, e: self.exception = e self.tb = traceback.format_exc()
if not title or title == _('Unknown'):
if not title or title == _('Unknown') or 'USER_CONTENT' in title:
def __init__(self, raw, codec, title): self.doctype = raw[:4] self.length, self.num_items = struct.unpack('>LL', raw[4:12]) raw = raw[12:] pos = 0 self.mi = MetaInformation(_('Unknown'), [_('Unknown')]) self.has_fake_cover = True left = self.num_items
_('You are tying to save files into the calibre '
_('You are trying to save files into the calibre '
def save_to_disk(self, checked, single_dir=False, single_format=None): rows = self.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self, _('Cannot save to disk'), _('No books selected'), show=True) path = choose_dir(self, 'save to disk dialog', _('Choose destination directory')) if not path: return dpath = os.path.abspath(path).replace('/', os.sep) lpath = self.library_view.model().db.library_path.replace('/', os.sep) if dpath.startswith(lpath): return error_dialog(self, _('Not allowed'), _('You are tying to save files into the calibre ' 'library. This can cause corruption of your ' 'library. Save to disk is meant to export ' 'files from your calibre library elsewhere.'), show=True)
stylesheet = None for item in self.oeb.manifest: if item.media_type.lower() in OEB_STYLES: stylesheet = item break
if stylesheet is not None: from cssutils.css import CSSRule for lb in XPath('//h:ul[@class]|//h:ol[@class]')(root): sel = '.'+lb.get('class') for rule in stylesheet.data.cssRules.rulesOfType(CSSRule.STYLE_RULE): if sel == rule.selectorList.selectorText: val = rule.style.removeProperty('margin-left') pval = rule.style.getProperty('padding-left') if val and not pval: rule.style.setProperty('padding-left', val)
def workaround_ade_quirks(self): ''' Perform various markup transforms to get the output to render correctly in the quirky ADE. ''' from calibre.ebooks.oeb.base import XPath, XHTML, OEB_STYLES, barename, urlunquote
collections = [x.strip() for x in
collections = [x.lower().strip() for x in
def sync_booklists(self, booklists, end_session=True): debug_print('PRS505: started sync_booklists') c = self.initialize_XML_cache() blists = {} for i in c.paths: if booklists[i] is not None: blists[i] = booklists[i] opts = self.settings() if opts.extra_customization: collections = [x.strip() for x in opts.extra_customization.split(',')] else: collections = [] debug_print('PRS505: collection fields:', collections) c.update(blists, collections) c.write()
res = re.sub('(?<=\n)\n{2}', u'<p>\u00a0</p>\n', res)
res = re.sub('(?<=\n)\n{2}', u'<p>\u00a0</p>\n'.encode('utf-8'), res)
def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.rtf2xml.ParseRtf import RtfInvalidCodeException self.options = options self.log = log self.log('Converting RTF to XML...') #Name of the preprocesssed RTF file fname = self.preprocess(stream.name) try: xml = self.generate_xml(fname) except RtfInvalidCodeException, e: raise ValueError(_('This RTF file has a feature calibre does not ' 'support. Convert it to HTML first and then try it.\n%s')%e)
self.datetime = time.gmtime()
try: self.datetime = time.gmtime(os.path.getctime(self.path)) except: self.datetime = time.gmtime()
def __init__(self, prefix, lpath, size=None, other=None): from calibre.ebooks.metadata.meta import path_to_ext
if islinux and not linux_scanner.ok: raise RuntimeError('DeviceScanner requires the /sys filesystem to work.')
def __init__(self, *args): if isosx and osx_scanner is None: raise RuntimeError('The Python extension usbobserver must be available on OS X.') if islinux and not linux_scanner.ok: raise RuntimeError('DeviceScanner requires the /sys filesystem to work.') self.scanner = win_scanner if iswindows else osx_scanner if isosx else linux_scanner self.devices = []
dev.reset(detected_device=detected_device,
try: dev.reset(detected_device=detected_device,
def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) dev.reset(detected_device=detected_device, report_progress=self.report_progress) try: dev.open() except: prints('Unable to open device', str(dev)) traceback.print_exc() continue self.connected_device = dev self.connected_device_kind = device_kind self.connected_slot(True, device_kind) return True return False
try:
def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) dev.reset(detected_device=detected_device, report_progress=self.report_progress) try: dev.open() except: prints('Unable to open device', str(dev)) traceback.print_exc() continue self.connected_device = dev self.connected_device_kind = device_kind self.connected_slot(True, device_kind) return True return False
prints('Unable to open device', str(dev)) traceback.print_exc()
tb = traceback.format_exc() if DEBUG or tb not in self.reported_errors: self.reported_errors.add(tb) prints('Unable to open device', str(dev)) prints(tb)
def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) dev.reset(detected_device=detected_device, report_progress=self.report_progress) try: dev.open() except: prints('Unable to open device', str(dev)) traceback.print_exc() continue self.connected_device = dev self.connected_device_kind = device_kind self.connected_slot(True, device_kind) return True return False
prints('Connect to device failed, retrying in 5 seconds...')
if DEBUG: prints('Connect to device failed, retrying in 5 seconds...')
def detect_device(self): self.scanner.scan() if self.is_device_connected: connected, detected_device = \ self.scanner.is_device_connected(self.connected_device, only_presence=True) if not connected: self.connected_device_removed() else: possibly_connected_devices = [] for device in self.devices: if device in self.ejected_devices: continue possibly_connected, detected_device = \ self.scanner.is_device_connected(device) if possibly_connected: possibly_connected_devices.append((device, detected_device)) if possibly_connected_devices: if not self.do_connect(possibly_connected_devices, device_kind='device'): prints('Connect to device failed, retrying in 5 seconds...') time.sleep(5) if not self.do_connect(possibly_connected_devices, device_kind='usb'): prints('Device connect failed again, giving up')
prints('Device connect failed again, giving up')
if DEBUG: prints('Device connect failed again, giving up')
def detect_device(self): self.scanner.scan() if self.is_device_connected: connected, detected_device = \ self.scanner.is_device_connected(self.connected_device, only_presence=True) if not connected: self.connected_device_removed() else: possibly_connected_devices = [] for device in self.devices: if device in self.ejected_devices: continue possibly_connected, detected_device = \ self.scanner.is_device_connected(device) if possibly_connected: possibly_connected_devices.append((device, detected_device)) if possibly_connected_devices: if not self.do_connect(possibly_connected_devices, device_kind='device'): prints('Connect to device failed, retrying in 5 seconds...') time.sleep(5) if not self.do_connect(possibly_connected_devices, device_kind='usb'): prints('Device connect failed again, giving up')
self.valign = 'baseline' self.nest = False
def __init__(self): self.rendered = False self.left = 0. self.halign = 'auto' self.indent = 0. self.fsize = 3 self.ids = set() self.valign = 'baseline' self.nest = False self.italic = False self.bold = False self.strikethrough = False self.underline = False self.preserve = False self.family = 'serif' self.bgcolor = 'transparent' self.fgcolor = 'black' self.href = None self.list_num = 0 self.attrib = {}
and self.valign == other.valign \
def __eq__(self, other): return self.fsize == other.fsize \ and self.italic == other.italic \ and self.bold == other.bold \ and self.href == other.href \ and self.valign == other.valign \ and self.preserve == other.preserve \ and self.family == other.family \ and self.bgcolor == other.bgcolor \ and self.fgcolor == other.fgcolor \ and self.strikethrough == other.strikethrough \ and self.underline == other.underline
valign = istate.valign
def mobimlize_content(self, tag, text, bstate, istates): 'Convert text content' if text or tag != 'br': bstate.content = True istate = istates[-1] para = bstate.para if tag in SPECIAL_TAGS and not text: para = para if para is not None else bstate.body elif para is None or tag in ('td', 'th'): body = bstate.body if bstate.pbreak: etree.SubElement(body, MBP('pagebreak')) bstate.pbreak = False bstate.istate = None bstate.anchor = None parent = bstate.nested[-1] if bstate.nested else bstate.body indent = istate.indent left = istate.left if isinstance(indent, basestring): indent = 0 if indent < 0 and abs(indent) < left: left += indent indent = 0 elif indent != 0 and abs(indent) < self.profile.fbase: indent = (indent / abs(indent)) * self.profile.fbase if tag in NESTABLE_TAGS and not istate.rendered: para = wrapper = etree.SubElement( parent, XHTML(tag), attrib=istate.attrib) bstate.nested.append(para) if tag == 'li' and len(istates) > 1: istates[-2].list_num += 1 para.attrib['value'] = str(istates[-2].list_num) elif tag in NESTABLE_TAGS and istate.rendered: para = wrapper = bstate.nested[-1] elif left > 0 and indent >= 0: ems = self.profile.mobi_ems_per_blockquote para = wrapper = etree.SubElement(parent, XHTML('blockquote')) para = wrapper emleft = int(round(left / self.profile.fbase)) - ems emleft = min((emleft, 10)) while emleft > ems/2.0: para = etree.SubElement(para, XHTML('blockquote')) emleft -= ems else: para = wrapper = etree.SubElement(parent, XHTML('p')) bstate.inline = bstate.para = para vspace = bstate.vpadding + bstate.vmargin bstate.vpadding = bstate.vmargin = 0 if tag not in TABLE_TAGS: wrapper.attrib['height'] = self.mobimlize_measure(vspace) para.attrib['width'] = self.mobimlize_measure(indent) elif tag == 'table' and vspace > 0: vspace = int(round(vspace / self.profile.fbase)) while vspace > 0: wrapper.addprevious(etree.Element(XHTML('br'))) vspace -= 1 if istate.halign != 'auto' and isinstance(istate.halign, (str, unicode)): para.attrib['align'] = istate.halign istate.rendered = True pstate = bstate.istate if tag in CONTENT_TAGS: bstate.inline = para pstate = bstate.istate = None etree.SubElement(para, XHTML(tag), attrib=istate.attrib) elif tag in TABLE_TAGS: para.attrib['valign'] = 'top' if istate.ids: last = bstate.body[-1] for id in istate.ids: last.addprevious(etree.Element(XHTML('a'), attrib={'id': id})) istate.ids.clear() if not text: return if not pstate or istate != pstate: inline = para valign = istate.valign fsize = istate.fsize href = istate.href if not href: bstate.anchor = None elif pstate and pstate.href == href: inline = bstate.anchor else: inline = etree.SubElement(inline, XHTML('a'), href=href) bstate.anchor = inline if valign == 'super': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sup')) elif valign == 'sub': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sub')) elif fsize != 3: inline = etree.SubElement(inline, XHTML('font'), size=str(fsize)) if istate.family == 'monospace': inline = etree.SubElement(inline, XHTML('tt')) if istate.italic: inline = etree.SubElement(inline, XHTML('i')) if istate.bold: inline = etree.SubElement(inline, XHTML('b')) if istate.bgcolor is not None and istate.bgcolor != 'transparent' : inline = etree.SubElement(inline, XHTML('span'), bgcolor=istate.bgcolor) if istate.fgcolor != 'black': inline = etree.SubElement(inline, XHTML('font'), color=unicode(istate.fgcolor)) if istate.strikethrough: inline = etree.SubElement(inline, XHTML('s')) if istate.underline: inline = etree.SubElement(inline, XHTML('u')) bstate.inline = inline bstate.istate = istate inline = bstate.inline content = self.preize_text(text) if istate.preserve else [text] for item in content: if isinstance(item, basestring): if len(inline) == 0: inline.text = (inline.text or '') + item else: last = inline[-1] last.tail = (last.tail or '') + item else: inline.append(item)
if valign == 'super': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sup')) elif valign == 'sub': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sub')) elif fsize != 3:
if fsize != 3:
def mobimlize_content(self, tag, text, bstate, istates): 'Convert text content' if text or tag != 'br': bstate.content = True istate = istates[-1] para = bstate.para if tag in SPECIAL_TAGS and not text: para = para if para is not None else bstate.body elif para is None or tag in ('td', 'th'): body = bstate.body if bstate.pbreak: etree.SubElement(body, MBP('pagebreak')) bstate.pbreak = False bstate.istate = None bstate.anchor = None parent = bstate.nested[-1] if bstate.nested else bstate.body indent = istate.indent left = istate.left if isinstance(indent, basestring): indent = 0 if indent < 0 and abs(indent) < left: left += indent indent = 0 elif indent != 0 and abs(indent) < self.profile.fbase: indent = (indent / abs(indent)) * self.profile.fbase if tag in NESTABLE_TAGS and not istate.rendered: para = wrapper = etree.SubElement( parent, XHTML(tag), attrib=istate.attrib) bstate.nested.append(para) if tag == 'li' and len(istates) > 1: istates[-2].list_num += 1 para.attrib['value'] = str(istates[-2].list_num) elif tag in NESTABLE_TAGS and istate.rendered: para = wrapper = bstate.nested[-1] elif left > 0 and indent >= 0: ems = self.profile.mobi_ems_per_blockquote para = wrapper = etree.SubElement(parent, XHTML('blockquote')) para = wrapper emleft = int(round(left / self.profile.fbase)) - ems emleft = min((emleft, 10)) while emleft > ems/2.0: para = etree.SubElement(para, XHTML('blockquote')) emleft -= ems else: para = wrapper = etree.SubElement(parent, XHTML('p')) bstate.inline = bstate.para = para vspace = bstate.vpadding + bstate.vmargin bstate.vpadding = bstate.vmargin = 0 if tag not in TABLE_TAGS: wrapper.attrib['height'] = self.mobimlize_measure(vspace) para.attrib['width'] = self.mobimlize_measure(indent) elif tag == 'table' and vspace > 0: vspace = int(round(vspace / self.profile.fbase)) while vspace > 0: wrapper.addprevious(etree.Element(XHTML('br'))) vspace -= 1 if istate.halign != 'auto' and isinstance(istate.halign, (str, unicode)): para.attrib['align'] = istate.halign istate.rendered = True pstate = bstate.istate if tag in CONTENT_TAGS: bstate.inline = para pstate = bstate.istate = None etree.SubElement(para, XHTML(tag), attrib=istate.attrib) elif tag in TABLE_TAGS: para.attrib['valign'] = 'top' if istate.ids: last = bstate.body[-1] for id in istate.ids: last.addprevious(etree.Element(XHTML('a'), attrib={'id': id})) istate.ids.clear() if not text: return if not pstate or istate != pstate: inline = para valign = istate.valign fsize = istate.fsize href = istate.href if not href: bstate.anchor = None elif pstate and pstate.href == href: inline = bstate.anchor else: inline = etree.SubElement(inline, XHTML('a'), href=href) bstate.anchor = inline if valign == 'super': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sup')) elif valign == 'sub': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sub')) elif fsize != 3: inline = etree.SubElement(inline, XHTML('font'), size=str(fsize)) if istate.family == 'monospace': inline = etree.SubElement(inline, XHTML('tt')) if istate.italic: inline = etree.SubElement(inline, XHTML('i')) if istate.bold: inline = etree.SubElement(inline, XHTML('b')) if istate.bgcolor is not None and istate.bgcolor != 'transparent' : inline = etree.SubElement(inline, XHTML('span'), bgcolor=istate.bgcolor) if istate.fgcolor != 'black': inline = etree.SubElement(inline, XHTML('font'), color=unicode(istate.fgcolor)) if istate.strikethrough: inline = etree.SubElement(inline, XHTML('s')) if istate.underline: inline = etree.SubElement(inline, XHTML('u')) bstate.inline = inline bstate.istate = istate inline = bstate.inline content = self.preize_text(text) if istate.preserve else [text] for item in content: if isinstance(item, basestring): if len(inline) == 0: inline.text = (inline.text or '') + item else: last = inline[-1] last.tail = (last.tail or '') + item else: inline.append(item)
def mobimlize_elem(self, elem, stylizer, bstate, istates):
def mobimlize_elem(self, elem, stylizer, bstate, istates, ignore_valign=False):
def mobimlize_elem(self, elem, stylizer, bstate, istates): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return style = stylizer.style(elem) # <mbp:frame-set/> does not exist lalalala if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') \ or style['visibility'] == 'hidden': return tag = barename(elem.tag) istate = copy.copy(istates[-1]) istate.rendered = False istate.list_num = 0 istates.append(istate) left = 0 display = style['display'] isblock = not display.startswith('inline') isblock = isblock and style['float'] == 'none' isblock = isblock and tag != 'br' if isblock: bstate.para = None istate.halign = style['text-align'] istate.indent = style['text-indent'] if style['margin-left'] == 'auto' \ and style['margin-right'] == 'auto': istate.halign = 'center' margin = asfloat(style['margin-left']) padding = asfloat(style['padding-left']) if tag != 'body': left = margin + padding istate.left += left vmargin = asfloat(style['margin-top']) bstate.vmargin = max((bstate.vmargin, vmargin)) vpadding = asfloat(style['padding-top']) if vpadding > 0: bstate.vpadding += bstate.vmargin bstate.vmargin = 0 bstate.vpadding += vpadding elif not istate.href: margin = asfloat(style['margin-left']) padding = asfloat(style['padding-left']) lspace = margin + padding if lspace > 0: spaces = int(round((lspace * 3) / style['font-size'])) elem.text = (u'\xa0' * spaces) + (elem.text or '') margin = asfloat(style['margin-right']) padding = asfloat(style['padding-right']) rspace = margin + padding if rspace > 0: spaces = int(round((rspace * 3) / style['font-size'])) if len(elem) == 0: elem.text = (elem.text or '') + (u'\xa0' * spaces) else: last = elem[-1] last.text = (last.text or '') + (u'\xa0' * spaces) if bstate.content and style['page-break-before'] in PAGE_BREAKS: bstate.pbreak = True istate.fsize = self.mobimlize_font(style['font-size']) istate.italic = True if style['font-style'] == 'italic' else False weight = style['font-weight'] istate.bold = weight in ('bold', 'bolder') or asfloat(weight) > 400 istate.preserve = (style['white-space'] in ('pre', 'pre-wrap')) istate.bgcolor = style['background-color'] istate.fgcolor = style['color'] istate.strikethrough = style['text-decoration'] == 'line-through' istate.underline = style['text-decoration'] == 'underline' if 'monospace' in style['font-family']: istate.family = 'monospace' elif 'sans-serif' in style['font-family']: istate.family = 'sans-serif' else: istate.family = 'serif' valign = style['vertical-align'] if valign in ('super', 'text-top') or asfloat(valign) > 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'super' elif valign == 'sub' or asfloat(valign) < 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'sub' else: istate.valign = 'baseline' if 'id' in elem.attrib: istate.ids.add(elem.attrib['id']) if 'name' in elem.attrib: istate.ids.add(elem.attrib['name']) if tag == 'a' and 'href' in elem.attrib: istate.href = elem.attrib['href'] istate.attrib.clear() if tag == 'img' and 'src' in elem.attrib: istate.attrib['src'] = elem.attrib['src'] istate.attrib['align'] = 'baseline' for prop in ('width', 'height'): if style[prop] != 'auto': value = style[prop] if value == getattr(self.profile, prop): result = '100%' else: try: ems = int(round(float(value) / self.profile.fbase)) except: continue result = "%dem" % ems istate.attrib[prop] = result elif tag == 'hr' and asfloat(style['width']) > 0: prop = style['width'] / self.profile.width istate.attrib['width'] = "%d%%" % int(round(prop * 100)) elif display == 'table': tag = 'table' elif display == 'table-row': tag = 'tr' elif display == 'table-cell': tag = 'td' if tag in TABLE_TAGS and self.ignore_tables: tag = 'span' if tag == 'td' else 'div'
valign = style['vertical-align'] if valign in ('super', 'text-top') or asfloat(valign) > 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'super' elif valign == 'sub' or asfloat(valign) < 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'sub' else: istate.valign = 'baseline'
def mobimlize_elem(self, elem, stylizer, bstate, istates): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return style = stylizer.style(elem) # <mbp:frame-set/> does not exist lalalala if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') \ or style['visibility'] == 'hidden': return tag = barename(elem.tag) istate = copy.copy(istates[-1]) istate.rendered = False istate.list_num = 0 istates.append(istate) left = 0 display = style['display'] isblock = not display.startswith('inline') isblock = isblock and style['float'] == 'none' isblock = isblock and tag != 'br' if isblock: bstate.para = None istate.halign = style['text-align'] istate.indent = style['text-indent'] if style['margin-left'] == 'auto' \ and style['margin-right'] == 'auto': istate.halign = 'center' margin = asfloat(style['margin-left']) padding = asfloat(style['padding-left']) if tag != 'body': left = margin + padding istate.left += left vmargin = asfloat(style['margin-top']) bstate.vmargin = max((bstate.vmargin, vmargin)) vpadding = asfloat(style['padding-top']) if vpadding > 0: bstate.vpadding += bstate.vmargin bstate.vmargin = 0 bstate.vpadding += vpadding elif not istate.href: margin = asfloat(style['margin-left']) padding = asfloat(style['padding-left']) lspace = margin + padding if lspace > 0: spaces = int(round((lspace * 3) / style['font-size'])) elem.text = (u'\xa0' * spaces) + (elem.text or '') margin = asfloat(style['margin-right']) padding = asfloat(style['padding-right']) rspace = margin + padding if rspace > 0: spaces = int(round((rspace * 3) / style['font-size'])) if len(elem) == 0: elem.text = (elem.text or '') + (u'\xa0' * spaces) else: last = elem[-1] last.text = (last.text or '') + (u'\xa0' * spaces) if bstate.content and style['page-break-before'] in PAGE_BREAKS: bstate.pbreak = True istate.fsize = self.mobimlize_font(style['font-size']) istate.italic = True if style['font-style'] == 'italic' else False weight = style['font-weight'] istate.bold = weight in ('bold', 'bolder') or asfloat(weight) > 400 istate.preserve = (style['white-space'] in ('pre', 'pre-wrap')) istate.bgcolor = style['background-color'] istate.fgcolor = style['color'] istate.strikethrough = style['text-decoration'] == 'line-through' istate.underline = style['text-decoration'] == 'underline' if 'monospace' in style['font-family']: istate.family = 'monospace' elif 'sans-serif' in style['font-family']: istate.family = 'sans-serif' else: istate.family = 'serif' valign = style['vertical-align'] if valign in ('super', 'text-top') or asfloat(valign) > 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'super' elif valign == 'sub' or asfloat(valign) < 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'sub' else: istate.valign = 'baseline' if 'id' in elem.attrib: istate.ids.add(elem.attrib['id']) if 'name' in elem.attrib: istate.ids.add(elem.attrib['name']) if tag == 'a' and 'href' in elem.attrib: istate.href = elem.attrib['href'] istate.attrib.clear() if tag == 'img' and 'src' in elem.attrib: istate.attrib['src'] = elem.attrib['src'] istate.attrib['align'] = 'baseline' for prop in ('width', 'height'): if style[prop] != 'auto': value = style[prop] if value == getattr(self.profile, prop): result = '100%' else: try: ems = int(round(float(value) / self.profile.fbase)) except: continue result = "%dem" % ems istate.attrib[prop] = result elif tag == 'hr' and asfloat(style['width']) > 0: prop = style['width'] / self.profile.width istate.attrib['width'] = "%d%%" % int(round(prop * 100)) elif display == 'table': tag = 'table' elif display == 'table-row': tag = 'tr' elif display == 'table-cell': tag = 'td' if tag in TABLE_TAGS and self.ignore_tables: tag = 'span' if tag == 'td' else 'div'
self.qaction.triggered.connect(self.add_books_to_library)
def location_selected(self, loc): enabled = loc != 'library' self.qaction.setEnabled(enabled) self.qaction.triggered.connect(self.add_books_to_library)
if data.get('id', None) == self.data.get('id', None):
if data.get('id', True) == self.data.get('id', False):
def show_data(self, data): self.animation.stop() if data.get('id', None) == self.data.get('id', None): return self.data = {'id':data.get('id', None)} if data.has_key('cover'): self.pixmap = QPixmap.fromImage(data.pop('cover')) if self.pixmap.isNull(): self.pixmap = self.default_pixmap else: self.pixmap = self.default_pixmap self.do_layout() self.update() self.animation.start()
WARNING: This completely regenrates your datbase. You will
WARNING: This completely regenerates your datbase. You will
def restore_database_option_parser(): parser = get_parser(_( ''' %prog restore_database [options] Restore this database from the metadata stored in OPF files in each directory of the calibre library. This is useful if your metadata.db file has been corrupted. WARNING: This completely regenrates your datbase. You will lose stored per-book conversion settings and custom recipes. ''')) return parser
if size < 1024*1024: divisor, suffix = 1024., "KB" elif size < 1024*1024*1024: divisor, suffix = 1024*1024, "MB" elif size < 1024*1024*1024*1024: divisor, suffix = 1024*1024*1024, "GB"
for i, candidate in enumerate(('KB', 'MB', 'GB', 'TB', 'PB', 'EB')): if size < 1024**(i+2): divisor, suffix = 1024**(i+1), candidate break
def human_readable(size): """ Convert a size in bytes into a human readable form """ divisor, suffix = 1, "B" if size < 1024*1024: divisor, suffix = 1024., "KB" elif size < 1024*1024*1024: divisor, suffix = 1024*1024, "MB" elif size < 1024*1024*1024*1024: divisor, suffix = 1024*1024*1024, "GB" size = str(float(size)/divisor) if size.find(".") > -1: size = size[:size.find(".")+2] if size.endswith('.0'): size = size[:-2] return size + " " + suffix
raise 'Bad domain name (circular) at ' + str(off)
raise ValueError('Bad domain name (circular) at ' + str(off))
def readName(self): '''Reads a domain name from the packet''' result = '' off = self.offset next = -1 first = off
raise 'Bad domain name at ' + str(off)
raise ValueError('Bad domain name at ' + str(off))
def readName(self): '''Reads a domain name from the packet''' result = '' off = self.offset next = -1 first = off
self.current_index = len(self.ids)
def do_one(self, id): remove, add, au, aus, do_aus, rating, pub, do_series, \ do_autonumber, do_remove_format, remove_format, do_swap_ta, \ do_remove_conv, do_auto_author, series, do_series_restart, \ series_start_value, do_title_case, clear_series = self.args
self.search_box.set_search_string(ss)
self.search_box.clear_to_help()
def delete_search_button_clicked(self): if not confirm('<p>'+_('The selected search will be ' '<b>permanently deleted</b>. Are you sure?') +'</p>', 'saved_search_delete', self): return idx = self.currentIndex if idx < 0: return ss = self.saved_searches.lookup(unicode(self.currentText())) self.saved_searches.delete(unicode(self.currentText())) self.clear_to_help() self.search_box.set_search_string(ss) self.emit(SIGNAL('changed()'))
item = QListWidgetItem(BooksModel.headers[col], self.columns)
try: item = QListWidgetItem(BooksModel.headers[col], self.columns) except KeyError: continue
def __init__(self, window, db, server=None): ResizableDialog.__init__(self, window) self.ICON_SIZES = {0:QSize(48, 48), 1:QSize(32,32), 2:QSize(24,24)} self._category_model = CategoryModel()
if processed or plumber.input_fmt.lower() in ('pdf', 'rb'):
if hasattr(self.pathtoopf, 'manifest'): self.pathtoopf = write_oebbook(self.pathtoopf, self.base) elif processed or plumber.input_fmt.lower() in ('pdf', 'rb'):
def __enter__(self, processed=False): self.delete_on_exit = [] self._tdir = TemporaryDirectory('_ebook_iter') self.base = self._tdir.__enter__() from calibre.ebooks.conversion.plumber import Plumber, create_oebbook plumber = Plumber(self.pathtoebook, self.base, self.log) plumber.setup_options() if self.pathtoebook.lower().endswith('.opf'): plumber.opts.dont_package = True if hasattr(plumber.opts, 'no_process'): plumber.opts.no_process = True
if hasattr(self.pathtoopf, 'manifest'): self.pathtoopf = write_oebbook(self.pathtoopf, self.base)
def __enter__(self, processed=False): self.delete_on_exit = [] self._tdir = TemporaryDirectory('_ebook_iter') self.base = self._tdir.__enter__() from calibre.ebooks.conversion.plumber import Plumber, create_oebbook plumber = Plumber(self.pathtoebook, self.base, self.log) plumber.setup_options() if self.pathtoebook.lower().endswith('.opf'): plumber.opts.dont_package = True if hasattr(plumber.opts, 'no_process'): plumber.opts.no_process = True
print "count found in cache: %d, count of files in metadata: %d, need_sync: %s" % \ (len(bl_cache), len(bl), need_sync)
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(path) in self.FORMATS: try: lpath = path.partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/')
print "Add book to metatdata: " print "prefix: " + prefix
def add_books_to_metadata(self, locations, metadata, booklists): metadata = iter(metadata) for i, location in enumerate(locations): self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...')) info = metadata.next() blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
print "path: " + lpath
def add_books_to_metadata(self, locations, metadata, booklists): metadata = iter(metadata) for i, location in enumerate(locations): self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...')) info = metadata.next() blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
self.search_restriction.currentIndexChanged[str].connect(self.apply_search_restriction)
self.search_restriction.activated[str].connect(self.apply_search_restriction)
def initialize(self, library_path, db, listener, actions): opts = self.opts self.last_time = datetime.datetime.now() self.preferences_action, self.quit_action = actions self.library_path = library_path self.spare_servers = [] self.must_restart_before_config = False # Initialize fontconfig in a separate thread as this can be a lengthy # process if run for the first time on this machine from calibre.utils.fonts import fontconfig self.fc = fontconfig self.listener = Listener(listener) self.check_messages_timer = QTimer() self.connect(self.check_messages_timer, SIGNAL('timeout()'), self.another_instance_wants_to_talk) self.check_messages_timer.start(1000)
self.search.clear_to_help()
self.apply_search_restriction('')
def saved_searches_changed(self): p = prefs['saved_searches'].keys() p.sort() t = unicode(self.search_restriction.currentText()) self.search_restriction.clear() # rebuild the restrictions combobox using current saved searches self.search_restriction.addItem('') for s in p: self.search_restriction.addItem(s) if t: if t in p: # redo the current restriction, if there was one self.search_restriction.setCurrentIndex(self.search_restriction.findText(t)) # self.tags_view.set_search_restriction(t) else: self.search_restriction.setCurrentIndex(0) self.search.clear_to_help()
if extension == '.pdf' or extension == '.epub':
elif extension == '.pdf' or extension == '.epub':
def delete_books(self, paths, end_session=True): for i, path in enumerate(paths): self.report_progress((i+1) / float(len(paths)), _('Removing books from device...')) path = self.normalize_path(path) # print "Delete file normalized path: " + path extension = os.path.splitext(path)[1]
if extension == '.html':
else:
def delete_books(self, paths, end_session=True): for i, path in enumerate(paths): self.report_progress((i+1) / float(len(paths)), _('Removing books from device...')) path = self.normalize_path(path) # print "Delete file normalized path: " + path extension = os.path.splitext(path)[1]
query = '' for e in (opts.title, opts.author, opts.publisher): if e is not None: query += ' ' + e
query = ' '.join([e for e in (opts.title, opts.author, opts.publisher) \ if e is not None ])
def build_combined(base_url, opts): query = '' for e in (opts.title, opts.author, opts.publisher): if e is not None: query += ' ' + e query = query.strip() if len(query) == 0: raise ISBNDBError('You must specify at least one of --author, --title or --publisher') query = re.sub(r'\s+', '+', query) if isinstance(query, unicode): query = query.encode('utf-8') return base_url+'index1=combined&value1='+quote(query, '+')
ans = [] for x in tans: add = True for y in ans: if y.isbn == x.isbn: add = False if add: ans.append(x) return ans
return dict((book.isbn, book) for book in tans).values()
def create_books(opts, args, timeout=5.): base_url = BASE_URL%dict(key=args[1]) if opts.isbn is not None: url = build_isbn(base_url, opts) else: url = build_combined(base_url, opts) if opts.verbose: print ('ISBNDB query: '+url) tans = [ISBNDBMetadata(book) for book in fetch_metadata(url, timeout=timeout)] ans = [] for x in tans: add = True for y in ans: if y.isbn == x.isbn: add = False if add: ans.append(x) return ans
pdf = open(pdf_n, 'rw+b')
pdf = open(pdf_n, 'rwb')
def extract_content(self, output_dir): self.log.info('Extracting PDF...')
b, _, e = x.rpartition('.') if not b and e: b = e e = ''
b, e = os.path.splitext(x) if e == '.': e = ''
def shorten_components_to(length, components): filepath = os.sep.join(components) extra = len(filepath) - length if extra < 1: return components delta = int(ceil(extra/float(len(components)))) ans = [] for x in components: if delta > len(x): r = x[0] if x is components[-1] else '' else: if x is components[-1]: b, _, e = x.rpartition('.') if not b and e: b = e e = '' r = b[:-delta]+e if r.startswith('.'): r = x[0]+r else: r = x[:-delta] r = r.strip() if not r: r = x.strip()[0] if x.strip() else 'x' ans.append(r) if len(os.sep.join(ans)) > length: return shorten_components_to(length, ans) return ans
self.root = os.getcwdu()
try: self.root = os.getcwdu() except: pass
def __init__(self, stream, mode='r', root=None): try: self.archive = ZipFile(stream, mode=mode) except BadZipfile: raise EPubException("not a ZIP .epub OCF container") self.root = root if self.root is None: self.root = os.getcwdu() if hasattr(stream, 'name'): self.root = os.path.abspath(os.path.dirname(stream.name)) super(OCFZipReader, self).__init__()
files = [] blocks = []
def compareFileStream(file1, file2): return cmp(file1.fileName, file2.fileName)
self.Parse(inputFile); def Parse(self, inputFile):
self.Open(inputFile) def Open(self, inputFile):
def __init__(self, inputFile = None): if inputFile != None: self.Parse(inputFile);
self.Parse(snbFile) snbFile.close() def Parse(self, snbFile, metaOnly = False):
def Parse(self, inputFile): self.fileName = inputFile snbFile = open(self.fileName, "rb") snbFile.seek(0) # Read header vmbr = snbFile.read(44) (self.magic, self.rev80, self.revA3, self.revZ1, self.fileCount, self.vfatSize, self.vfatCompressed, self.binStreamSize, self.plainStreamSizeUncompressed, self.revZ2) = struct.unpack('>8siiiiiiiii', vmbr)
except EOFError, e:
except Exception, e:
def Parse(self, inputFile): self.fileName = inputFile snbFile = open(self.fileName, "rb") snbFile.seek(0) # Read header vmbr = snbFile.read(44) (self.magic, self.rev80, self.revA3, self.revZ1, self.fileCount, self.vfatSize, self.vfatCompressed, self.binStreamSize, self.plainStreamSizeUncompressed, self.revZ2) = struct.unpack('>8siiiiiiiii', vmbr)
snbFile.close()
def Parse(self, inputFile): self.fileName = inputFile snbFile = open(self.fileName, "rb") snbFile.seek(0) # Read header vmbr = snbFile.read(44) (self.magic, self.rev80, self.revA3, self.revZ1, self.fileCount, self.vfatSize, self.vfatCompressed, self.binStreamSize, self.plainStreamSizeUncompressed, self.revZ2) = struct.unpack('>8siiiiiiiii', vmbr)
print "File Name:\t", self.fileName
if self.fileName: print "File Name:\t", self.fileName
def Dump(self): print "File Name:\t", self.fileName print "File Count:\t", self.fileCount print "VFAT Size(Compressed):\t%d(%d)" % (self.vfatSize, self.vfatCompressed) print "Binary Stream Size:\t", self.binStreamSize print "Plain Stream Uncompressed Size:\t", self.plainStreamSizeUncompressed print "Binary Block Count:\t", self.binBlock print "Plain Block Count:\t", self.plainBlock for i in range(self.fileCount): print "File ", i f = self.files[i] print "File Name: ", f.fileName print "File Attr: ", f.attr print "File Size: ", f.fileSize print "Block Index: ", f.blockIndex print "Content Offset: ", f.contentOffset tempFile = open("/tmp/" + f.fileName, 'wb') tempFile.write(f.fileBody) tempFile.close()
.format(fmt, fname, id_, fmt.upper()) for fmt in
.format(f, fname, id_, f.upper()) for f in
def browse_booklist_page(self, ids=None, sort=None): if sort == 'null': sort = None if ids is None: ids = json.dumps('[]') try: ids = json.loads(ids) except: raise cherrypy.HTTPError(404, 'invalid ids') summs = [] for id_ in ids: try: id_ = int(id_) mi = self.db.get_metadata(id_, index_is_id=True) except: continue args, fmt, fmts, fname = self.browse_get_book_args(mi, id_) args['other_formats'] = '' other_fmts = [x for x in fmts if x.lower() != fmt.lower()] if other_fmts: ofmts = [u'<a href="/get/{0}/{1}_{2}.{0}" title="{3}">{3}</a>'\ .format(fmt, fname, id_, fmt.upper()) for fmt in other_fmts] ofmts = ', '.join(ofmts) args['other_formats'] = u'<strong>%s: </strong>' % \ _('Other formats') + ofmts
fmt_sidx(m.series_index[0], use_roman=True), m.series[0])
fmt_sidx(m.series_index[0], use_roman=True), unicode(m.series[0]))
def default_cover(self): ''' Create a generic cover for books that dont have a cover ''' from calibre.ebooks.metadata import authors_to_string, fmt_sidx if self.no_default_cover: return None self.log('Generating default cover') m = self.oeb.metadata title = unicode(m.title[0]) authors = [unicode(x) for x in m.creator if x.role == 'aut'] series_string = None if m.series and m.series_index: series_string = _('Book %s of %s')%( fmt_sidx(m.series_index[0], use_roman=True), m.series[0])
default=False,
default=True,
def tpl_replace(objtplname) :
self.opts.log.info(" refreshing cache at '%s'" % self.__archive_path) self.opts.log.info(' thumb_width: %1.2f" => %1.2f"' %
self.opts.log.warning(" invalidating cache at '%s'" % self.__archive_path) self.opts.log.warning(' thumb_width changed: %1.2f" => %1.2f"' %
def __init__(self, db, opts, plugin, report_progress=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authorClip = opts.authorClip self.__authors = None self.__basename = opts.basename self.__bookmarked_books = None self.__booksByAuthor = None self.__booksByDateRead = None self.__booksByTitle = None self.__booksByTitle_noSeriesPrefix = None self.__cache_dir = os.path.join(config_dir, 'caches', 'catalog') self.__archive_path = os.path.join(self.__cache_dir, "thumbs.zip") self.__catalogPath = PersistentTemporaryDirectory("_epub_mobi_catalog", prefix='') self.__contentDir = os.path.join(self.catalogPath, "content") self.__currentStep = 0.0 self.__creator = opts.creator self.__db = db self.__descriptionClip = opts.descriptionClip self.__error = None self.__generateForKindle = True if (self.opts.fmt == 'mobi' and \ self.opts.output_profile and \ self.opts.output_profile.startswith("kindle")) else False self.__generateRecentlyRead = True if self.opts.generate_recently_added \ and self.opts.connected_kindle \ and self.generateForKindle \ else False self.__genres = None self.genres = [] self.__genre_tags_dict = None self.__htmlFileList_1 = [] self.__htmlFileList_2 = [] self.__markerTags = self.getMarkerTags() self.__ncxSoup = None self.__output_profile = None self.__playOrder = 1 self.__plugin = plugin self.__progressInt = 0.0 self.__progressString = '' f, _, p = opts.read_book_marker.partition(':') self.__read_book_marker = {'field':f, 'pattern':p} f, p, hr = self.opts.merge_comments.split(':') self.__merge_comments = {'field':f, 'position':p, 'hr':hr} self.__reporter = report_progress self.__stylesheet = stylesheet self.__thumbs = None self.__thumbWidth = 0 self.__thumbHeight = 0 self.__title = opts.catalog_title self.__totalSteps = 8.0 self.__useSeriesPrefixInTitlesSection = False self.__verbose = opts.verbose
if not mi.title:
if mi.is_null('title'):
def swap(a): if ',' in a: parts = a.split(',', 1) else: parts = a.split(None, 1) if len(parts) > 1: t = parts[-1] parts = parts[:-1] parts.insert(0, t) return ' '.join(parts)
self.comments = 'SUMMARY:\n'+summ.string
self.comments = 'SUMMARY:\n'+summ
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
pt.write(self.db.format(id, format, index_is_id=True))
src = self.db.format(id, format, index_is_id=True, as_file=True) shutil.copyfileobj(src, pt)
def get_preferred_formats_from_ids(self, ids, formats, paths=False, set_metadata=False, specific_format=None, exclude_auto=False, mode='r+b'): ans = [] need_auto = [] if specific_format is not None: formats = [specific_format.lower()] for id in ids: format = None fmts = self.db.formats(id, index_is_id=True) if not fmts: fmts = '' db_formats = set(fmts.lower().split(',')) available_formats = set([f.lower() for f in formats]) u = available_formats.intersection(db_formats) for f in formats: if f.lower() in u: format = f break if format is not None: pt = PersistentTemporaryFile(suffix='.'+format) pt.write(self.db.format(id, format, index_is_id=True)) pt.flush() if set_metadata: _set_metadata(pt, self.db.get_metadata(id, get_cover=True, index_is_id=True), format) pt.close() if paths else pt.seek(0) ans.append(pt) else: need_auto.append(id) if not exclude_auto: ans.append(None) return ans, need_auto
def regenerate_headers(self, len_updated_metadata):
def regenerate_headers(self, updated_md_len):
def regenerate_headers(self, len_updated_metadata):
sh = sorted(headers,key=lambda x:(headers[x],headers[x])) sh.remove('metadata') sh.append('metadata')
def regenerate_headers(self, len_updated_metadata):
for tag in sh[:-1]:
for tag in headers.keys():
def regenerate_headers(self, len_updated_metadata):
if b['offset'] < original_md_offset:
if b['offset'] <= original_md_offset:
def regenerate_headers(self, len_updated_metadata):
ths.write(self.encode_vwi(b['offset'] - original_md_len)) ths.write(self.encode_vwi(b['len_uncomp']))
ths.write(self.encode_vwi(b['offset'] + delta)) if tag == 'metadata': ths.write(self.encode_vwi(updated_md_len)) else: ths.write(self.encode_vwi(b['len_uncomp']))
def regenerate_headers(self, len_updated_metadata):
new_md_offset = (len(self.data) - self.base - original_md_len) new_md_len = len_updated_metadata - 1 - len('metadata') - 1 ths.write('c') ths.write(self.encode_vwi(len('metadata'))) ths.write('metadata') ths.write(self.encode_vwi(1)) ths.write(self.encode_vwi(new_md_offset)) ths.write(self.encode_vwi(new_md_len)) ths.write(self.encode_vwi(0)) self.sorted_headers = sh
def regenerate_headers(self, len_updated_metadata):
self.stream.write(updated_metadata)
def update(self,mi): # Collect the original metadata self.get_original_metadata()
mi = MetaInformation(title="My New Title", authors=['Smith, John']) set_metadata(open(sys.argv[1], 'rb'), mi)
if False: print get_metadata(open(sys.argv[1], 'rb')) else: import cStringIO data = open(sys.argv[1], 'rb') stream = cStringIO.StringIO() stream.write(data.read()) mi = MetaInformation(title="A Marvelously Long Title", authors=['Riker, Gregory; Riker, Charles']) set_metadata(stream, mi) tokens = sys.argv[1].rpartition('.') updated_data = open(tokens[0]+'-updated' + '.' + tokens[2],'wb') updated_data.write(stream.getvalue()) updated_data.close()
def set_metadata(stream, mi): mu = MetadataUpdater(stream) mu.update(mi) return
self.connect(self.action_sync, SIGNAL('triggered(bool)'), self._sync_menu.trigger_default)
def create_device_menu(self): self._sync_menu = DeviceMenu(self) self.action_sync.setMenu(self._sync_menu) self.connect(self._sync_menu, SIGNAL('sync(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)'), self.dispatch_sync_event) self.connect(self.action_sync, SIGNAL('triggered(bool)'), self._sync_menu.trigger_default) self._sync_menu.fetch_annotations.connect(self.fetch_annotations)
break
continue
def get_matches(self, location, query): matches = set([]) if query and query.strip(): location = location.lower().strip()
self.log("found " + unicode(self.html_preprocess_sections) +
self.log("marked " + unicode(self.html_preprocess_sections) +
def chapter_head(self, match): chap = match.group('chap') title = match.group('title') if not title: self.html_preprocess_sections = self.html_preprocess_sections + 1 self.log("found " + unicode(self.html_preprocess_sections) + " chapters. - " + unicode(chap)) return '<h2>'+chap+'</h2>\n' else: self.html_preprocess_sections = self.html_preprocess_sections + 1 self.log("found " + unicode(self.html_preprocess_sections) + " chapters & titles. - " + unicode(chap) + ", " + unicode(title)) return '<h2>'+chap+'</h2>\n<h3>'+title+'</h3>\n'
html = re.sub(r"\s*<p>\s*", "\n<p>", html)
html = re.sub(r"\s*<p(?P<style>[^>]*)>\s*", "\n<p"+"\g<style>"+">", html)
def __call__(self, html): self.log("********* Preprocessing HTML *********")
elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query)
else: if ignore_search_restriction: q = u'%s' % query else: q = u'%s (%s)' % (self.search_restriction, query)
def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map) # when return_matches, do not update the maps! self._map_filtered = list(self._map) return [] matches = sorted(self.parse(q)) ans = [id for id in self._map if id in matches] if return_matches: return ans self._map_filtered = ans return []
return []
return
def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map) # when return_matches, do not update the maps! self._map_filtered = list(self._map) return [] matches = sorted(self.parse(q)) ans = [id for id in self._map if id in matches] if return_matches: return ans self._map_filtered = ans return []
return []
def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map) # when return_matches, do not update the maps! self._map_filtered = list(self._map) return [] matches = sorted(self.parse(q)) ans = [id for id in self._map if id in matches] if return_matches: return ans self._map_filtered = ans return []
base = base or self.width
if base is None: base = self.width
def _unit_convert(self, value, base=None, font=None): ' Return value in pts' if isinstance(value, (int, long, float)): return value try: return float(value) * 72.0 / self._profile.dpi except: pass result = value m = self.UNIT_RE.match(value) if m is not None and m.group(1): value = float(m.group(1)) unit = m.group(2) if unit == '%': base = base or self.width result = (value / 100.0) * base elif unit == 'px': result = value * 72.0 / self._profile.dpi elif unit == 'in': result = value * 72.0 elif unit == 'pt': result = value elif unit == 'em': font = font or self.fontSize result = value * font elif unit in ('ex', 'en'): # This is a hack for ex since we have no way to know # the x-height of the font font = font or self.fontSize result = value * font * 0.5 elif unit == 'pc': result = value * 12.0 elif unit == 'mm': result = value * 0.04 elif unit == 'cm': result = value * 0.40 return result
for key in item.attrib.keys(): if key.endswith('scheme'): scheme = item.get(key)
for xkey in item.attrib.keys(): if xkey.endswith('scheme'): scheme = item.get(xkey)
def process_encryption(self, encfile, opf, log): key = None for item in opf.identifier_iter(): scheme = None for key in item.attrib.keys(): if key.endswith('scheme'): scheme = item.get(key) if (scheme and scheme.lower() == 'uuid') or \ (item.text and item.text.startswith('urn:uuid:')): key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes))