rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
max_results=10, rlang='all'):
max_results=20, rlang='all'):
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=10, rlang='all'): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 11)
assert (max_results < 11)
assert (max_results < 21)
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=10, rlang='all'): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 11)
def populate(self, entries, br, verbose=False): res = [] for x in entries: entry = self.get_individual_metadata(x, br, verbose)
def fetchdatathread(self, qbr, qsync, nb, url, verbose): try: browser = qbr.get(True) entry = self.get_individual_metadata(url, browser, verbose) except: report(verbose) entry = None finally: qbr.put(browser, True) qsync.put(nb, True) return entry def producer(self, sync, urls, br, verbose=False): for i in xrange(len(...
def populate(self, entries, br, verbose=False): res = [] for x in entries: entry = self.get_individual_metadata(x, br, verbose) if entry is not None: mi = self.fill_MI(entry, verbose) if mi is not None: mi.tags, atag = self.get_tags(entry, verbose) if atag: tags = self.get_individual_metadata(mi.tags, br, verbose) if t...
tags = self.get_individual_metadata(mi.tags, br, verbose) if tags is not None: mi.tags = self.get_tags(tags, verbose)[0] res.append(mi) return res
threadbis = ThreadwithResults(self.fetchdatathread, br, syncbis, nb, mi.tags, verbose) self.thread[nb] = threadbis self.nbtag +=1 threadbis.start() def populate(self, entries, ibr, verbose=False, brcall=3): br = Queue(brcall) cbr = Queue(brcall-1) syncp = Queue(1) syncc = Queue(len(entries)) for i in xrange(brcall-1...
def populate(self, entries, br, verbose=False): res = [] for x in entries: entry = self.get_individual_metadata(x, br, verbose) if entry is not None: mi = self.fill_MI(entry, verbose) if mi is not None: mi.tags, atag = self.get_tags(entry, verbose) if atag: tags = self.get_individual_metadata(mi.tags, br, verbose) if t...
ISBN, publisher or keywords. Will fetch a maximum of 10 matches,
ISBN, publisher or keywords. Will fetch a maximum of 20 matches,
def option_parser(): parser = OptionParser(textwrap.dedent(\ _('''\ %prog [options] Fetch book metadata from Amazon. You must specify one of title, author, ISBN, publisher or keywords. Will fetch a maximum of 10 matches, so you should make your query as specific as possible. You can chose the language for metadata ret...
def setup_printer(opts, for_comic=False):
def get_pdf_printer(opts, for_comic=False):
def setup_printer(opts, for_comic=False): from calibre.gui2 import is_ok_to_use_qt if not is_ok_to_use_qt(): raise Exception('Not OK to use Qt') printer = get_pdf_printer() custom_size = get_custom_size(opts) if opts.output_profile.short_name == 'default': if custom_size is None: printer.setPaperSize(paper_size(opts....
printer = get_pdf_printer()
printer = QPrinter(QPrinter.HighResolution)
def setup_printer(opts, for_comic=False): from calibre.gui2 import is_ok_to_use_qt if not is_ok_to_use_qt(): raise Exception('Not OK to use Qt') printer = get_pdf_printer() custom_size = get_custom_size(opts) if opts.output_profile.short_name == 'default': if custom_size is None: printer.setPaperSize(paper_size(opts....
printer.setPageMargins(0, 0, 0, 0, QPrinter.Point)
printer.setPageMargins(opts.margin_left, opts.margin_top, opts.margin_right, opts.margin_bottom, QPrinter.Point)
def setup_printer(opts, for_comic=False): from calibre.gui2 import is_ok_to_use_qt if not is_ok_to_use_qt(): raise Exception('Not OK to use Qt') printer = get_pdf_printer() custom_size = get_custom_size(opts) if opts.output_profile.short_name == 'default': if custom_size is None: printer.setPaperSize(paper_size(opts....
printer = setup_printer(opts, for_comic=for_comic)
printer = get_pdf_printer(opts, for_comic=for_comic)
def get_printer_page_size(opts, for_comic=False): printer = setup_printer(opts, for_comic=for_comic) size = printer.paperSize(QPrinter.Millimeter) return size.width() / 10., size.height() / 10.
def get_printer(self, set_horz_margins=False): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) if set_horz_margins: printer.setPageMargins(0., self.opts.margin_top, 0., self.opts.margin_bottom, QPrinter.Point) else: printer.setPageMargins(0, 0, 0, 0, Q...
def get_printer(self, set_horz_margins=False): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) if set_horz_margins: printer.setPageMargins(0., self.opts.margin_top, 0., self.opts.margin_bottom, QPrinter.Point) else: printer.setPageMargins(0, 0, 0, 0, Q...
self.logger.debug('\tRendering item %s as %i' % (os.path.basename(str(self.view.url().toLocalFile())), len(self.combine_queue))) printer = self.get_printer(set_horz_margins=True)
self.logger.debug('\tRendering item %s as %i.pdf' % (os.path.basename(str(self.view.url().toLocalFile())), len(self.combine_queue))) printer = get_pdf_printer(self.opts)
def _render_html(self, ok): if ok: item_path = os.path.join(self.tmp_path, '%i.pdf' % len(self.combine_queue)) self.logger.debug('\tRendering item %s as %i' % (os.path.basename(str(self.view.url().toLocalFile())), len(self.combine_queue))) printer = self.get_printer(set_horz_margins=True) printer.setOutputFileName(item...
printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat)
printer = get_pdf_printer(self.opts)
def render_images(self, outpath, mi, items): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) print...
printer.setFullPage(True)
def render_images(self, outpath, mi, items): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) print...
try: article = self.feed_objects[f].articles[a] except: self.log.exception('Failed to get article object for postprocessing') pass else: self.populate_article_metadata(article, ans, first_fetch)
if job_info: url, f, a, feed_len = job_info try: article = self.feed_objects[f].articles[a] except: self.log.exception('Failed to get article object for postprocessing') pass else: self.populate_article_metadata(article, ans, first_fetch)
def _postprocess_html(self, soup, first_fetch, job_info): if self.no_stylesheets: for link in list(soup.findAll('link', type=re.compile('css')))+list(soup.findAll('style')): link.extract() head = soup.find('head') if not head: head = soup.find('body') if not head: head = soup.find(True) style = BeautifulSoup(u'<style t...
if barename(child.tag) == 'body':
if isinstance(child.tag, (unicode, str)) and barename(child.tag) == 'body':
def first_pass(data): try: data = etree.fromstring(data, parser=parser) 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 = etree.fromstring(data, parser=parser) except etree.XMLSyntaxError...
elem.getparent().remove(elem)
if hasattr(elem, 'getparent'): elem.getparent().remove(elem) else: elem = SPAN(elem)
def _generate(self, article, style=None, extra_css=None): content = article.content if article.content else '' summary = article.summary if article.summary else '' text = content if len(content) > len(summary) else summary head = HEAD(TITLE(article.title)) if style: head.append(STYLE(style, type='text/css')) if extra_c...
aTag.insert(0, escape(title['author']))
aTag.insert(0, title['author'])
def generateHTMLDescriptions(self): # Write each title to a separate HTML file in contentdir if self.verbose: print self.updateProgressFullStep("generateHTMLDescriptions()")
etree.SubElement(trees[subitem].find(".//body"), "img").text = line[len(CALIBRE_SNB_IMG_TAG):]
prefix = ProcessFileName(os.path.dirname(self.item.href)) if prefix != '': etree.SubElement(trees[subitem].find(".//body"), "img").text = \ prefix + '_' + line[len(CALIBRE_SNB_IMG_TAG):] else: etree.SubElement(trees[subitem].find(".//body"), "img").text = \ line[len(CALIBRE_SNB_IMG_TAG):]
def mlize(self): output = [ u'' ] stylizer = Stylizer(self.item.data, self.item.href, self.oeb_book, self.opts, self.opts.output_profile) content = unicode(etree.tostring(self.item.data.find(XHTML('body')), encoding=unicode)) content = self.remove_newlines(content) trees = { } for subitem, subtitle in self.subitems: sn...
return
id_ = elem.get('id', None) if id_: elem.clear() elem.text = None elem.set('id', id_) else: return
def mobimlize_elem(self, elem, stylizer, bstate, istates, ignore_valign=False): 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['visib...
date = self.check_timestamp(record, book, path) if date is not None: self.update_text_record(record, book, date, path, i)
self.update_text_record(record, book, path, i)
def update(self, booklists, collections_attributes): debug_print('Starting update', collections_attributes) for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) debug_print('Updating XML Cache:', i) root = self.record_roots[i] lpath_map = self.build_lpath_map(root) for book in booklist: pa...
def check_timestamp(self, record, book, path):
def update_text_record(self, record, book, path, bl_index):
def check_timestamp(self, record, book, path): ''' Checks the timestamp in the Sony DB against the file. If different, return the file timestamp. Otherwise return None. ''' timestamp = os.path.getmtime(path) date = strftime(timestamp) if date != record.get('date', None): return date return None
Checks the timestamp in the Sony DB against the file. If different, return the file timestamp. Otherwise return None.
Update the Sony database from the book. This is done if the timestamp in the db differs from the timestamp on the file.
def check_timestamp(self, record, book, path): ''' Checks the timestamp in the Sony DB against the file. If different, return the file timestamp. Otherwise return None. ''' timestamp = os.path.getmtime(path) date = strftime(timestamp) if date != record.get('date', None): return date return None
return date return None def update_text_record(self, record, book, date, path, bl_index): ''' Update the Sony database from the book. This is done if the timestamp in the db differs from the timestamp on the file. ''' record.set('date', date)
record.set('date', date)
def check_timestamp(self, record, book, path): ''' Checks the timestamp in the Sony DB against the file. If different, return the file timestamp. Otherwise return None. ''' timestamp = os.path.getmtime(path) date = strftime(timestamp) if date != record.get('date', None): return date return None
self.library.layout().addWidget(self.cover_flow)
self.cb_layout.addWidget(self.cover_flow)
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 c...
self.library_view.verticalHeader().sectionClicked.connect(self.view_specific_book)
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 c...
if not is_gui_thread(): return Dispatcher(self.recount)(*args)
def recount(self, *args): if not is_gui_thread(): # Re-call in GUI thread return Dispatcher(self.recount)(*args) ci = self.currentIndex() if not ci.isValid(): ci = self.indexAt(QPoint(10, 10)) try: self.model().refresh() except: #Database connection could be closed if an integrity check is happening pass if ci.isValid(...
if ci.isValid(): self.scrollTo(ci, QTreeView.PositionAtTop)
if path: idx = self.model().index_for_path(path) if idx.isValid(): self.setCurrentIndex(idx) self.scrollTo(idx, QTreeView.PositionAtCenter)
def recount(self, *args): if not is_gui_thread(): # Re-call in GUI thread return Dispatcher(self.recount)(*args) ci = self.currentIndex() if not ci.isValid(): ci = self.indexAt(QPoint(10, 10)) try: self.model().refresh() except: #Database connection could be closed if an integrity check is happening pass if ci.isValid(...
translated.append(word)
translated.append(word.capitalize())
def generateSortTitle(self, title): # Convert the actual title to a string suitable for sorting. # Ignore leading stop words # Optionally convert leading numbers to strings from calibre.ebooks.metadata import title_sort # Strip stop words title_words = title_sort(title).split() translated = []
target = open(targetpath, "wb")
try: target = open(targetpath, "wb") except IOError: targetpath = sanitize_file_name(targetpath) target = open(targetpath, "wb")
def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. if targetpath[-1:] == "/": targetpath = targetpath[:-1]
abspath = os.path.abspath(*file_name.split('/'))
abspath = os.path.abspath(os.path.join(*file_name.split('/')))
def is_match(fname): return (name is not None and fname == name) or \ (match is not None and match.search(fname) is not None)
massage.append((re.compile(r'&(\S+?);'), lambda match: entity_to_unicode(match, encoding=self.encoding)))
enc = 'cp1252' if callable(self.encoding) or self.encoding is None else self.encoding massage.append((re.compile(r'&(\S+?);'), lambda match: entity_to_unicode(match, encoding=enc)))
def index_to_soup(self, url_or_raw, raw=False): ''' Convenience method that takes an URL to the index page and returns a `BeautifulSoup <http://www.crummy.com/software/BeautifulSoup/documentation.html>`_ of it.
try: self.parent.contents.remove(self) except ValueError: pass
idx = None for i, x in enumerate(self.parent.contents): if x is self: idx = i break if idx is not None: self.parent.contents.pop(idx)
def extract(self): """Destructively rips this element out of the tree.""" if self.parent: try: self.parent.contents.remove(self) except ValueError: pass
from PyQt4.Qt import QFile, QImage, Qt
def setup_desktop_integration(self): try: from PyQt4.Qt import QFile, QImage, Qt
render_svg(QFile(I('mimetypes/lrf.svg')), 'calibre-lrf.png')
render_img('mimetypes/lrf.svg', 'calibre-lrf.png')
def setup_desktop_integration(self): try: from PyQt4.Qt import QFile, QImage, Qt
p = QImage(I('lt.png')).scaledToHeight(128, Qt.SmoothTransformation) p.save('calibre-gui.png')
render_img('lt.png', 'calibre-gui.png')
def setup_desktop_integration(self): try: from PyQt4.Qt import QFile, QImage, Qt
render_svg(QFile(I('viewer.svg')), 'calibre-viewer.png')
render_img('viewer.svg', 'calibre-viewer.png')
def setup_desktop_integration(self): try: from PyQt4.Qt import QFile, QImage, Qt
def render_svg(image, dest, width=128, height=128): from PyQt4.QtGui import QPainter, QImage from PyQt4.QtSvg import QSvgRenderer image = image.readAll() if hasattr(image, 'readAll') else image svg = QSvgRenderer(image) painter = QPainter() image = QImage(width, height, QImage.Format_ARGB32) painter.begin(image) painte...
def render_img(image, dest, width=128, height=128): from PyQt4.Qt import QImage, Qt img = QImage(I(image)).scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) img.save(dest)
def render_svg(image, dest, width=128, height=128): from PyQt4.QtGui import QPainter, QImage from PyQt4.QtSvg import QSvgRenderer image = image.readAll() if hasattr(image, 'readAll') else image svg = QSvgRenderer(image) painter = QPainter() image = QImage(width, height, QImage.Format_ARGB32) painter.begin(image) painte...
sys.argv = old_argv
def main(): # Handy tab-completers for %cd, %run, import etc. # Try commenting this out if you have completion problems/slowness import ipy_stock_completers # uncomment if you want to get ipython -p sh behaviour # without having to use command line switches import ipy_profile_sh # Configure your favourite editor? #...
href = item.abshref(val)
href = urlnormalize(item.abshref(val))
def serialize_elem(self, elem, item, nsrmap=NSRMAP): buffer = self.buffer if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) not in nsrmap: return tag = prefixname(elem.tag, nsrmap) # Previous layers take care of @name id = elem.attrib.pop('id', None) if id is not None: href = '#'.join((item.href, id)) of...
def get(name, category, field='name'): ans = self.conn.get('SELECT DISTINCT %s FROM %s'%(field, name)) ans = [x[0].strip() for x in ans] try: ans.remove('') except ValueError: pass categories[category] = list(map(Tag, ans)) tags = categories[category] if name != 'data': for tag in tags: id = self.conn.get('SELECT id FR...
for x in ('tags', 'series', 'news', 'publishers', 'authors'): query = 'SELECT id,name,count FROM tag_browser_'+x if sort_on_count: query += ' ORDER BY count DESC'
def get(name, category, field='name'): ans = self.conn.get('SELECT DISTINCT %s FROM %s'%(field, name)) ans = [x[0].strip() for x in ans] try: ans.remove('') except ValueError: pass categories[category] = list(map(Tag, ans)) tags = categories[category] if name != 'data': for tag in tags: id = self.conn.get('SELECT id FR...
for tag in tags: tag.count = self.conn.get('SELECT COUNT(format) FROM data WHERE format=?', (tag.name,), all=False) tags.sort(reverse=sort_on_count, cmp=(lambda x,y:cmp(x.count,y.count)) if sort_on_count else (lambda x,y:cmp(x.name, y.name))) for x in (('authors', 'author'), ('tags', 'tag'), ('publishers', 'publisher')...
query += ' ORDER BY name ASC' data = self.conn.get(query) category = x if x in ('series', 'news') else x[:-1] categories[category] = [Tag(r[1], count=r[2], id=r[0]) for r in data] categories['format'] = [] for fmt in self.conn.get('SELECT DISTINCT format FROM data'): fmt = fmt[0] count = self.conn.get('SELECT COUNT(id...
def get(name, category, field='name'): ans = self.conn.get('SELECT DISTINCT %s FROM %s'%(field, name)) ans = [x[0].strip() for x in ans] try: ans.remove('') except ValueError: pass categories[category] = list(map(Tag, ans)) tags = categories[category] if name != 'data': for tag in tags: id = self.conn.get('SELECT id FR...
re.compile(r'''<meta\s+?[^<>]+?content\s*=\s*['"][^'"]*?charset=([-a-z0-9]+)[^'"]*?['"][^<>]*>''',
re.compile(r'''<meta\s+?[^<>]*?content\s*=\s*['"][^'"]*?charset=([-a-z0-9]+)[^'"]*?['"][^<>]*>''',
def detect(aBuf): import calibre.ebooks.chardet.universaldetector as universaldetector u = universaldetector.UniversalDetector() u.reset() u.feed(aBuf) u.close() return u.result
self.write_rating = False
def __init__(self, window, rows, db): QDialog.__init__(self, window) Ui_MetadataBulkDialog.__init__(self) self.setupUi(self) self.db = db self.ids = [ db.id(r) for r in rows] self.write_series = False self.write_rating = False self.changed = False QObject.connect(self.button_box, SIGNAL("accepted()"), self.sync) QObjec...
QObject.connect(self.rating, SIGNAL('valueChanged(int)'), self.rating_changed)
def __init__(self, window, rows, db): QDialog.__init__(self, window) Ui_MetadataBulkDialog.__init__(self) self.setupUi(self) self.db = db self.ids = [ db.id(r) for r in rows] self.write_series = False self.write_rating = False self.changed = False QObject.connect(self.button_box, SIGNAL("accepted()"), self.sync) QObjec...
if self.write_rating:
if self.rating.value() != -1:
def sync(self): for id in self.ids: au = unicode(self.authors.text()) if au: au = string_to_authors(au) self.db.set_authors(id, au, notify=False) if self.auto_author_sort.isChecked(): aut = self.db.authors(id, index_is_id=True) aut = aut if aut else '' aut = [a.strip().replace('|', ',') for a in aut.strip().split(',')]...
FORMATS = ['epub', 'pdf', 'txt']
FORMATS = ['epub', 'pdf', 'htm', 'html', 'txt']
def can_handle(cls, dev, debug=False): return dev[-1] == '1.00' and not dev[-2] and not dev[-3]
if attr == 'series':
if attr == 'series' or getattr(book, 'series', None) == category:
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) collections = {} series_categories = set([]) # This map of sets is used to avoid linear searches when testing for # book equality collections_l...
'style="padding-right:2em">%s</td><td valign="top">%s</td></tr></table>'
'style="padding-right:2em; width:40%%">%s</td><td valign="top">%s</td></tr></table>'
def color_to_string(col): ans = '#000000' if col.isValid(): col = col.toRgb() if col.isValid(): ans = unicode(col.name()) return ans
_('Email to')+' '+account, self)
_('Email to')+' '+account)
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
_('Email to')+' '+account, self)
_('Email to')+' '+account+ _(' and delete from library'))
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
self.connect(action1, SIGNAL('a_s(QAction)'), self.action_triggered) self.connect(action2, SIGNAL('a_s(QAction)'), self.action_triggered)
action1.a_s.connect(self.action_triggered) action2.a_s.connect(self.action_triggered)
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
return self.stanza(search=kwargs.get('search', None), sortby=kwargs.get('sortby',None), authorid=kwargs.get('authorid',None), tagid=kwargs.get('tagid',None), seriesid=kwargs.get('seriesid',None), offset=kwargs.get('offset', 0))
return self.opds(version=0)
def index(self, **kwargs): 'The / URL' ua = cherrypy.request.headers.get('User-Agent', '').strip() want_opds = \ cherrypy.request.headers.get('Stanza-Device-Name', 919) != 919 or \ cherrypy.request.headers.get('Want-OPDS-Catalog', 919) != 919 or \ ua.startswith('Stanza')
'mp3', 'pdb', 'azw', 'azw1'):
'mp3', 'pdb', 'azw', 'azw1', 'fb2'):
def run(self, archive): is_rar = archive.lower().endswith('.rar') if is_rar: from calibre.libunrar import extract_member, names else: zf = ZipFile(archive, 'r')
self.view_menu.addAction(_('View specific format'))
ac = self.view_menu.addAction(_('View specific format')) ac.setShortcut(Qt.AltModifier+Qt.Key_V)
def __init__(self, listener, opts, actions, parent=None): self.preferences_action, self.quit_action = actions self.spare_servers = [] MainWindow.__init__(self, opts, parent) # 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...
if guess_mimetype(path)[0] == ('text/html'): data = self._reformat(data)
def ExtractFiles(self, output_dir=os.getcwdu()): for path in self.Contents(): lpath = os.path.join(output_dir, path) self._ensure_dir(lpath) try: data = self.GetFile(path) except: self.log.exception('Failed to extract %s from CHM, ignoring'%path) continue if lpath.find(';') != -1: # fix file names with ";<junk>" at the...
def _reformat(self, data):
def _reformat(self, data, htmlpath):
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... self.log.exception("Unable to parse html for cleaning, leaving it") return data # nuke javascript... [s.extract() for s in soup('script')] # remo...
for img in soup('img'): try: while img['src'].startswith('../'): img['src'] = img['src'][3:] img['src'] = img['src'].split(';')[0] except KeyError: pass
base = os.path.dirname(htmlpath) for img in soup('img', src=True): src = img['src'] ipath = os.path.join(base, *src.split('/')) if os.path.exists(ipath): continue src = src.split(';')[0] if not src: continue ipath = os.path.join(base, *src.split('/')) if not os.path.exists(ipath): while src.startswith('../'): src = src...
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... self.log.exception("Unable to parse html for cleaning, leaving it") return data # nuke javascript... [s.extract() for s in soup('script')] # remo...
self.workaround_sony_quirks()
def convert(self, oeb, output_path, input_plugin, opts, log): self.log, self.opts, self.oeb = log, opts, oeb
from calibre import browser
def fetch(self): if not self.isbn: return from calibre import browser from calibre.ebooks.metadata import MetaInformation import json br = browser() try: raw = br.open( 'http://status.calibre-ebook.com/library_thing/metadata/'+self.isbn ).read() data = json.loads(raw) if not data: return if 'error' in data: raise Excep...
results = sorted(results, cmp=lambda x, y : cmp( (x.comments.strip() if x.comments else ''), (y.comments.strip() if y.comments else '') ), reverse=True)
results = list(filter(filter_metadata_results, results)) check_for_covers(results) words = ("the", "a", "an", "of", "and") prefix_pat = re.compile(r'^(%s)\s+'%("|".join(words))) trailing_paren_pat = re.compile(r'\(.*\)$') whitespace_pat = re.compile(r'\s+') def sort_func(x, y): def cleanup_title(s): s = s.strip().lo...
def search(title=None, author=None, publisher=None, isbn=None, isbndb_key=None, verbose=0): assert not(title is None and author is None and publisher is None and \ isbn is None) from calibre.customize.ui import metadata_sources, migrate_isbndb_key migrate_isbndb_key() if isbn is not None: isbn = re.sub(r'[^a-zA-Z0-9]',...
pml = re.sub(r'\\.\d=""', '', pml) pml = re.sub(r'\\.=""', '', pml) pml = re.sub(r'\\.\d', '', pml) pml = re.sub(r'\\.', '', pml)
pml = re.sub(r'\\C\d=".+*"', '', pml) pml = re.sub(r'\\Fn=".+*"', '', pml) pml = re.sub(r'\\Sd=".+*"', '', pml) pml = re.sub(r'\\.=".+*"', '', pml) pml = re.sub(r'\\X\d', '', pml) pml = re.sub(r'\\S[pbd]', '', pml) pml = re.sub(r'\\Fn', '', pml)
def strip_pml(self, pml): pml = re.sub(r'\\.\d=""', '', pml) pml = re.sub(r'\\.=""', '', pml) pml = re.sub(r'\\.\d', '', pml) pml = re.sub(r'\\.', '', pml) pml = re.sub(r'\\a\d\d\d', '', pml) pml = re.sub(r'\\U\d\d\d\d', '', pml) pml.replace('\r\n', ' ') pml.replace('\n', ' ') pml.replace('\r', ' ')
return self.static('index.html')
return self.static('index.html').replace('{prefix}', self.opts.url_prefix)
def old(self, **kwargs): return self.static('index.html')
if ' href += '
if href.startswith(' href = href[1:]
def dump_text(self, elem, stylizer, page, tag_stack=[]): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return []
rows.append(u'<tr><td>%s</td><td>%s</td></tr>'%
rows.append(u'<tr><td>%s</td><td>&nbsp;</td><td>%s</td></tr>'%
def initialize(self, name, default, help): variables = sorted(FORMAT_ARG_DESCS.keys()) rows = [] for var in variables: rows.append(u'<tr><td>%s</td><td>%s</td></tr>'% (var, FORMAT_ARG_DESCS[var])) table = u'<table>%s</table>'%(u'\n'.join(rows)) self.template_variables.setText(table)
tmpl = preprocess_template(self.opt_template.text()) fa = {} try: safe_format(tmpl, fa) except Exception, err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + \ '<br>'+str(err), show=True) return False
def validate(self): # TODO: NEWMETA: I haven't figured out how to get the custom columns # into here, so for the moment make all templates valid. return True
if l == 3: return dt.strftime('%a') return dt.strftime('%A')
if l == 3: return strf('%a') return strf('%A')
def format_day(mo): l = len(mo.group(0)) if l == 1: return '%d'%dt.day if l == 2: return '%02d'%dt.day if l == 3: return dt.strftime('%a') return dt.strftime('%A')
if l == 3: return dt.strftime('%b') return dt.strftime('%B')
if l == 3: return strf('%b') return strf('%B')
def format_month(mo): l = len(mo.group(0)) if l == 1: return '%d'%dt.month if l == 2: return '%02d'%dt.month if l == 3: return dt.strftime('%b') return dt.strftime('%B')
error_dialog(None, _('Repairing failed'),
error_dialog(self.splash_screen, _('Repairing failed'),
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
candidate = choose_dir(None, 'choose calibre library',
candidate = choose_dir(self.splash_screen, 'choose calibre library',
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
error_dialog(None, _('Bad database location'),
error_dialog(self.splash_screen, _('Bad database location'),
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
repair = question_dialog(None, _('Corrupted database'),
repair = question_dialog(self.splash_screen, _('Corrupted database'),
def initialize_db(self): db = None try: db = LibraryDatabase2(self.library_path) except (sqlite.Error, DatabaseException): repair = question_dialog(None, _('Corrupted database'), _('Your calibre database appears to be corrupted. Do ' 'you want calibre to try and repair it automatically? ' 'If you say No, a new empty ca...
error_dialog(None, _('Bad database location'),
error_dialog(self.splash_screen, _('Bad database location'),
def initialize_db(self): db = None try: db = LibraryDatabase2(self.library_path) except (sqlite.Error, DatabaseException): repair = question_dialog(None, _('Corrupted database'), _('Your calibre database appears to be corrupted. Do ' 'you want calibre to try and repair it automatically? ' 'If you say No, a new empty ca...
self.sorted_on[1], reset=reset)
self.sorted_on[1], reset=False) if reset: self.reset()
def resort(self, reset=True): if self.sorted_on: self.sort(self.column_map.index(self.sorted_on[0]), self.sorted_on[1], reset=reset)
def icu_collator(s1, s2, func=None): return cmp(func(unicode(s1)), func(unicode(s2)))
def icu_collator(s1, s2): return strcmp(force_unicode(s1, 'utf-8'), force_unicode(s2, 'utf-8'))
def icu_collator(s1, s2, func=None): return cmp(func(unicode(s1)), func(unicode(s2)))
from calibre.utils.icu import sort_key self.conn.create_collation('icucollate', partial(icu_collator, func=sort_key))
self.conn.create_collation('icucollate', icu_collator)
def connect(self): self.conn = sqlite.connect(self.path, factory=Connection, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) self.conn.execute('pragma cache_size=5000') encoding = self.conn.execute('pragma encoding').fetchone()[0] c_ext_loaded = load_c_extensions(self.conn) self.conn.row_factory = sqlite.Row...
elif category == 'newest': ids = self.search_cache('')
all_ids = self.search_cache('') if category == 'newest': ids = all_ids
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
ids = self.search_cache('')
ids = all_ids
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
def get_sort_key(x): sk = x.s if isinstance(sk, unicode): sk = sort_key(sk) return sk kf = get_sort_key
kf = lambda x :sort_key(x.s)
def get_sort_key(x): sk = x.s if isinstance(sk, unicode): sk = sort_key(sk) return sk
self.logger.debug('Skipping article %s (%s) from feed %s as it is too old.'%(title, article.localtime.strftime('%a, %d %b, %Y %H:%M'), self.title))
t = strftime(u'%a, %d %b, %Y %H:%M', article.localtime.timetuple()) self.logger.debug('Skipping article %s (%s) from feed %s as it is too old.'% (title, t, self.title))
def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): self.title = unicode(title if title else _('Unknown feed')) self.description = '' self.image_url = None self.articles = [] self.added_articles = []
if DEBUG: prints('Save-to-disk using plugboard:', fmt, cpb)
prints('Save-to-disk using plugboard:', fmt, cpb)
def save_book_to_disk(id, db, root, opts, length): mi = db.get_metadata(id, index_is_id=True) available_formats = db.formats(id, index_is_id=True) if not available_formats: available_formats = [] else: available_formats = [x.lower().strip() for x in available_formats.split(',')] if opts.formats == 'all': asked_formats...
self.title = title if title else _('Unknown feed')
self.title = unicode(title if title else _('Unknown feed'))
def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): self.title = title if title else _('Unknown feed') self.description = '' self.image_url = None self.articles = [] self.added_articles = []
self._model.sorting_done.connect(self.sorting_done)
self._model.sorting_done.connect(self.sorting_done, type=Qt.QueuedConnection)
def __init__(self, parent, modelcls=BooksModel): QTableView.__init__(self, parent)
self.output_dir = os.getcwd()
self.output_dir = os.path.abspath(os.getcwdu())
def __init__(self, options, log, progress_reporter): ''' Initialize the recipe. :param options: Parsed commandline options :param parser: Command line option parser. Used to intelligently merge options. :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string mess...
self.output_dir = os.path.abspath(self.output_dir)
def __init__(self, options, log, progress_reporter): ''' Initialize the recipe. :param options: Parsed commandline options :param parser: Command line option parser. Used to intelligently merge options. :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string mess...
if ImageID == None:
if ImageID != None:
def delete_images(self, ImageID): if ImageID == None: path_prefix = '.kobo/images/' path = self._main_prefix + path_prefix + ImageID
if book['author_sort'][0] != current_letter :
if book['author_sort'][0].upper() != current_letter :
def generateHTMLByAuthor(self): # Write books by author A-Z if self.verbose: print self.updateProgressFullStep("generateHTMLByAuthor()") friendly_name = "By Author"
opts.creator = "calibre"
opts.creator = "Calibre"
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
self.db_book_uuid_cache = set()
def __init__(self): self.db_book_uuid_cache = set() self.device_error_dialog = error_dialog(self, _('Error'), _('Error communicating with device'), ' ') self.device_error_dialog.setModal(Qt.NonModal) self.device_connected = None self.emailer = Emailer() self.emailer.start() self.device_manager = DeviceManager(Dispatche...
if reset:
if reset or not hasattr(self, 'db_book_title_cache'): if not hasattr(self, 'library_view') or self.library_view is None: return
def set_books_in_library(self, booklists, reset=False): if reset: # First build a cache of the library, so the search isn't On**2 self.db_book_title_cache = {} self.db_book_uuid_cache = {} db = self.library_view.model().db for id in db.data.iterallids(): mi = db.get_metadata(id, index_is_id=True) title = re.sub('(?u)\W...
q = Queue.Queue() self.dispatch_signal.emit(q, args, kwargs) return q.get()
with self.lock: self.dispatch_signal.emit(self.q, args, kwargs) res = self.q.get() return res
def __call__(self, *args, **kwargs): q = Queue.Queue() self.dispatch_signal.emit(q, args, kwargs) return q.get()
sbase = max(sizes.items(), key=operator.itemgetter(1))[0]
try: sbase = max(sizes.items(), key=operator.itemgetter(1))[0] except: sbase = 12.0
def baseline_spine(self): sizes = defaultdict(float) for item in self.oeb.spine: html = item.data stylizer = self.stylizers[item] body = html.find(XHTML('body')) fsize = self.context.source.fbase self.baseline_node(body, stylizer, sizes, fsize) sbase = max(sizes.items(), key=operator.itemgetter(1))[0] self.oeb.logger.i...
cats = [(u'<li><a title="{2} {0}" href="/browse/category/{1}">&nbsp;</a>'
cats = [(u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
def getter(x): return category_meta[x]['name'].lower()
level = 1
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
level = self.tagstack.count_tags(tag) + 1
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
self.opentag('%s' % self.listtypes.get(name), {'class':"%s_%d" % (name, level) })
self.opentag('%s' % self.listtypes.get(list_class,'UL'), {'class': list_class })
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
self.opentag('%s' % self.listtypes.get(name))
self.opentag('%s' % self.listtypes.get(list_class,'UL'))
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
level = 1
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
level = self.tagstack.count_tags(tag) + 1
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
self.closetag(self.listtypes.get(name))
list_class = "%s_%d" % (name, level) self.closetag(self.listtypes.get(list_class,'UL'))
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
self.listtypes[name] = 'ul'
def s_text_list_level_style_bullet(self, tag, attrs): """ CSS doesn't have the ability to set the glyph to a particular character, so we just go through the available glyphs """ name = self.tagstack.rfindattr( (STYLENS,'name') ) self.listtypes[name] = 'ul' level = attrs[(TEXTNS,'level')] self.prevstyle = self.currentst...