pep8 and misc fixes

This commit is contained in:
Kovid Goyal 2019-03-13 09:21:07 +05:30
parent 5b76089839
commit 6ad22b392b
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
36 changed files with 99 additions and 71 deletions

View File

@ -106,6 +106,7 @@ class FormatsList(MutableBase, MutableSequence):
# }}}
# Lazy metadata getters {{{
ga = object.__getattribute__
sa = object.__setattr__
@ -223,6 +224,7 @@ def has_cover_getter(dbref, book_id, cache):
cache['has_cover'] = ret = _('Yes') if db.field_for('cover', book_id, default_value=False) else ''
return ret
fmt_custom = lambda x:list(x) if isinstance(x, tuple) else x
@ -276,6 +278,7 @@ def user_categories_getter(proxy_metadata):
ret = cache['user_categories'] = db.user_categories_for_books((book_id,), {book_id:proxy_metadata})[book_id]
return ret
getters = {
'title':simple_getter('title', _('Unknown')),
'title_sort':simple_getter('sort', _('Unknown')),

View File

@ -10,6 +10,7 @@ import os, re
from polyglot.builtins import unicode_type
def node_mountpoint(node):
def de_mangle(raw):

View File

@ -59,11 +59,11 @@ def build_template_regexp(template):
try:
template = template.rpartition('/')[2]
return re.compile(re.sub('{([^}]*)}', f, template) + '([_\d]*$)')
return re.compile(re.sub('{([^}]*)}', f, template) + r'([_\d]*$)')
except:
prints(u'Failed to parse template: %r'%template)
template = u'{title} - {authors}'
return re.compile(re.sub('{([^}]*)}', f, template) + '([_\d]*$)')
return re.compile(re.sub('{([^}]*)}', f, template) + r'([_\d]*$)')
def create_upload_path(mdata, fname, template, sanitize,

View File

@ -61,6 +61,7 @@ def substitute_entites(raw):
from calibre import xml_entity_to_unicode
return ENTITY_PATTERN.sub(xml_entity_to_unicode, raw)
_CHARSET_ALIASES = {"macintosh" : "mac-roman",
"x-sjis" : "shift-jis"}

View File

@ -368,7 +368,9 @@ class EPUBInput(InputFormatPlugin):
def add_from_li(li, parent):
href = text = None
for x in li.iterchildren(XHTML('a'), XHTML('span')):
text = etree.tostring(x, method='text', encoding=unicode_type, with_tail=False).strip() or ' '.join(x.xpath('descendant-or-self::*/@title')).strip()
text = etree.tostring(
x, method='text', encoding=unicode_type, with_tail=False).strip() or ' '.join(
x.xpath('descendant-or-self::*/@title')).strip()
href = x.get('href')
if href:
if href.startswith('#'):

View File

@ -309,7 +309,9 @@ class HeuristicProcessor(object):
if float(self.chapters_with_title) / float(hits) > .5:
title_req = True
strict_title = False
self.log.debug(unicode_type(type_name)+" had "+unicode_type(hits)+" hits - "+unicode_type(self.chapters_no_title)+" chapters with no title, "+
self.log.debug(
unicode_type(type_name)+" had "+unicode_type(hits)+
" hits - "+unicode_type(self.chapters_no_title)+" chapters with no title, "+
unicode_type(self.chapters_with_title)+" chapters with titles, "+
unicode_type(float(self.chapters_with_title) / float(hits))+" percent. ")
if type_name == 'common':

View File

@ -264,6 +264,7 @@ class DOCX(object):
except EnvironmentError:
pass
if __name__ == '__main__':
d = DOCX(sys.argv[-1], extract=False)
print(d.metadata)

View File

@ -95,6 +95,7 @@ def read_indent(parent, dest, XPath, get):
ans = _read_width(cs, get)
setattr(dest, 'indent', ans)
border_edges = ('left', 'top', 'right', 'bottom', 'insideH', 'insideV')

View File

@ -272,7 +272,7 @@ class OEB2HTMLInlineCSSizer(OEB2HTML):
# as a page break and remove all other page break types that might be set.
style_a = 'page-break-before: always; %s' % re.sub('page-break-[^:]+:[^;]+;?', '', style_a)
# Remove unnecessary spaces.
style_a = re.sub('\s{2,}', ' ', style_a).strip()
style_a = re.sub(r'\s{2,}', ' ', style_a).strip()
tags.append(tag)
# Remove attributes we won't want.

View File

@ -168,5 +168,6 @@ def main(args=sys.argv, logger=None):
logger.info(_('LRS written to ')+opts.out)
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@ -19,7 +19,7 @@ publisher_pat = re.compile(r'\{\\info.*?\{\\manager(.*?)(?<!\\)\}', re.DOTALL)
def get_document_info(stream):
"""
Extract the \info block from an RTF file.
Extract the \\info block from an RTF file.
Return the info block as a string and the position in the file at which it
starts.
@param stream: File like object pointing to the RTF file.

View File

@ -129,7 +129,7 @@ class Reader132(FormatReader):
if self.header_record.footnote_count > 0:
html += '<br /><h1>%s</h1>' % _('Footnotes')
footnoteids = re.findall(
'\w+(?=\x00)', self.section_data(self.header_record.footnote_offset).decode('cp1252' if self.encoding is None else self.encoding))
'\\w+(?=\x00)', self.section_data(self.header_record.footnote_offset).decode('cp1252' if self.encoding is None else self.encoding))
for fid, i in enumerate(range(self.header_record.footnote_offset + 1, self.header_record.footnote_offset + self.header_record.footnote_count)):
self.log.debug('Extracting footnote page %i' % i)
if fid < len(footnoteids):
@ -141,7 +141,7 @@ class Reader132(FormatReader):
if self.header_record.sidebar_count > 0:
html += '<br /><h1>%s</h1>' % _('Sidebar')
sidebarids = re.findall(
'\w+(?=\x00)', self.section_data(self.header_record.sidebar_offset).decode('cp1252' if self.encoding is None else self.encoding))
'\\w+(?=\x00)', self.section_data(self.header_record.sidebar_offset).decode('cp1252' if self.encoding is None else self.encoding))
for sid, i in enumerate(range(self.header_record.sidebar_offset + 1, self.header_record.sidebar_offset + self.header_record.sidebar_count)):
self.log.debug('Extracting sidebar page %i' % i)
if sid < len(sidebarids):

View File

@ -77,8 +77,8 @@ class MarkdownMLizer(OEB2HTML):
text = re.sub('(?msu)\n{7,}', '\n' * 6, text)
# Remove blank lines at beginning and end of document.
text = re.sub('^\s*', '', text)
text = re.sub('\s*$', '\n\n', text)
text = re.sub(r'^\s*', '', text)
text = re.sub(r'\s*$', '\n\n', text)
return text

View File

@ -23,7 +23,10 @@ from polyglot.builtins import unicode_type
def add_window_properties_for_menu(widget, object_path, bus):
op = unicode_type(object_path)
set_X_window_properties(widget.effectiveWinId(), _UNITY_OBJECT_PATH=op, _GTK_UNIQUE_BUS_NAME=unicode_type(bus.get_unique_name()), _GTK_MENUBAR_OBJECT_PATH=op)
set_X_window_properties(
widget.effectiveWinId(), _UNITY_OBJECT_PATH=op,
_GTK_UNIQUE_BUS_NAME=unicode_type(bus.get_unique_name()),
_GTK_MENUBAR_OBJECT_PATH=op)
class DBusMenu(QObject):

View File

@ -20,6 +20,7 @@ def log(*args, **kw):
print('DBusExport:', *args, **kw)
kw['file'].flush()
from calibre.ptempfile import PersistentTemporaryDirectory
@ -60,6 +61,7 @@ class IconCache(object):
# dir to decide whether it should look for new icons in the theme dir.
os.utime(self.icon_theme_path, None)
_icon_cache = None

View File

@ -136,7 +136,11 @@ class ConfigWidget(QWidget, Ui_ConfigWidget):
self.columns.setCurrentRow(idx+1)
def format_map(self):
formats = [unicode_type(self.columns.item(i).data(Qt.UserRole) or '') for i in range(self.columns.count()) if self.columns.item(i).checkState()==Qt.Checked]
formats = [
unicode_type(self.columns.item(i).data(Qt.UserRole) or '')
for i in range(self.columns.count())
if self.columns.item(i).checkState()==Qt.Checked
]
return formats
def use_subdirs(self):

View File

@ -197,6 +197,7 @@ class AuthorsEdit(QDialog):
authors[la] = author
self.author.setText('')
if __name__ == '__main__':
app = QApplication([])
d = AuthorsEdit(['kovid goyal', 'divok layog', 'other author'], ['kovid goyal', 'other author'])

View File

@ -139,6 +139,7 @@ class ImportOPML(QDialog):
QDialog.accept(self)
if __name__ == '__main__':
import sys
for group in import_opml(open(sys.argv[-1], 'rb').read()):

View File

@ -843,7 +843,7 @@ class PluginUpdaterDialog(SizePersistedDialog):
if heading_node.text_content().lower().find('version history') != -1:
div_node = spoiler_node.xpath('div')[0]
text = html.tostring(div_node, method='html', encoding=unicode_type)
return re.sub('<div\s.*?>', '<div>', text)
return re.sub(r'<div\s.*?>', '<div>', text)
except:
if DEBUG:
prints('======= MobileRead Parse Error =======')

View File

@ -169,6 +169,7 @@ class BlockingBusy(QDialog):
def reject(self):
pass # Cannot cancel this dialog
if __name__ == '__main__':
from PyQt5.Qt import QTimer
app = QApplication([])

View File

@ -28,6 +28,7 @@ def image_extensions():
image_extensions.ans = [bytes(x).decode('utf-8') for x in QImageReader.supportedImageFormats()]
return image_extensions.ans
# This is present for compatibility with old plugins, do not use
IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'gif', 'png', 'bmp']

View File

@ -7,23 +7,24 @@ __docformat__ = 'restructuredtext en'
import functools
from PyQt5.Qt import (Qt, QApplication, QStackedWidget, QMenu, QTimer,
QSizePolicy, QStatusBar, QLabel, QFont, QAction, QTabBar, QStyle,
QVBoxLayout, QWidget, QSplitter, QToolButton, QIcon, QPainter, QStyleOption)
from PyQt5.Qt import (
QAction, QApplication, QFont, QIcon, QLabel, QMenu, QPainter, QSizePolicy,
QSplitter, QStackedWidget, QStatusBar, QStyle, QStyleOption, Qt, QTabBar, QTimer,
QToolButton, QVBoxLayout, QWidget
)
from calibre.constants import __appname__, get_version, isosx
from calibre.customize.ui import find_plugin
from calibre.gui2 import config, error_dialog, gprefs, is_widescreen, open_url
from calibre.gui2.book_details import BookDetails
from calibre.gui2.layout_menu import LayoutMenu
from calibre.gui2.library.alternate_views import GridView
from calibre.gui2.library.views import BooksView, DeviceBooksView
from calibre.gui2.notify import get_notifier
from calibre.gui2.tag_browser.ui import TagBrowserWidget
from calibre.gui2.widgets import LayoutButton, Splitter
from calibre.utils.config import prefs
from calibre.utils.icu import sort_key
from calibre.constants import (__appname__, preferred_encoding,
get_version)
from calibre.gui2 import config, is_widescreen, gprefs, error_dialog, open_url
from calibre.gui2.library.views import BooksView, DeviceBooksView
from calibre.gui2.library.alternate_views import GridView
from calibre.gui2.widgets import Splitter, LayoutButton
from calibre.gui2.tag_browser.ui import TagBrowserWidget
from calibre.gui2.book_details import BookDetails
from calibre.gui2.notify import get_notifier
from calibre.gui2.layout_menu import LayoutMenu
from calibre.customize.ui import find_plugin
from calibre.utils.localization import localize_website_link
from polyglot.builtins import unicode_type

View File

@ -778,7 +778,7 @@ class BooksModel(QAbstractTableModel): # {{{
def func(idx):
val = fffunc(field_obj, idfunc(idx), default_value=0) or 0
if val is 0:
if val == 0:
return None
ans = u'%.1f' % (val * sz_mult)
return (u'<0.1' if ans == u'0.0' else ans)

View File

@ -418,5 +418,6 @@ def main():
QTimer.singleShot(10, doit)
app.exec_()
if __name__ == '__main__':
main()

View File

@ -34,7 +34,7 @@ from calibre.gui2.tweak_book.widgets import BusyCursor
from calibre.gui2.widgets2 import FlowLayout, HistoryComboBox
from calibre.utils.icu import primary_contains
from calibre.ebooks.conversion.search_replace import REGEX_FLAGS, compile_regular_expression
src/calibre/gui2/tweak_book/preferences.py
from polyglot.builtins import unicode_type
# The search panel {{{

View File

@ -281,8 +281,8 @@ class SendEmail(QWidget, Ui_Form):
_('You must either set both the username <b>and</b> password for '
'the mail server or no username and no password at all.')).exec_()
return False
if not (username and password) and not question_dialog(self,
_('Are you sure?'),
if not (username and password) and not question_dialog(
self, _('Are you sure?'),
_('No username and password set for mailserver. Most '
' mailservers need a username and password. Are you sure?')):
return False

View File

@ -437,7 +437,6 @@ def update_serialized_metadata(book, common_data=None):
plugboard_cache = common_data
from calibre.customize.ui import apply_null_metadata
with apply_null_metadata:
fmts = [fp.rpartition(os.extsep)[-1] for fp in book['fmts']]
mi, cdata = read_serialized_metadata(book)

View File

@ -177,7 +177,7 @@ class Dictionaries(object):
def __init__(self):
self.remove_hyphenation = re.compile('[\u2010-]+')
self.negative_pat = re.compile('-[.\d+]')
self.negative_pat = re.compile(r'-[.\d+]')
self.fix_punctuation_pat = re.compile(r'''[:.]''')
self.dictionaries = {}
self.word_cache = {}

View File

@ -398,6 +398,7 @@ class FontScanner(Thread):
prints()
prints()
font_scanner = FontScanner()
font_scanner.start()
@ -407,5 +408,6 @@ def force_rescan():
font_scanner.force_rescan()
font_scanner.run()
if __name__ == '__main__':
font_scanner.dump_fonts()

View File

@ -121,8 +121,8 @@ def fixattrs(attrs):
def onlywhite(line):
"""Return true if the line does only consist of whitespace characters."""
for c in line:
if c is not ' ' and c is not ' ':
return c is ' '
if c != ' ' and c != ' ':
return c == ' '
return line
@ -136,7 +136,7 @@ def optwrap(text):
newlines = 0
for para in text.split("\n"):
if len(para) > 0:
if para[0] is not ' ' and para[0] is not '-' and para[0] is not '*':
if para[0] != ' ' and para[0] != '-' and para[0] != '*':
for line in wrap(para, BODY_WIDTH):
result += line + "\n"
result += "\n"

View File

@ -329,7 +329,7 @@ def get_icon(path, pixmap_to_data=None, as_data=False, size=64):
from PyQt5.Qt import QImage, Qt
names.sort(key=numeric_sort_key)
for name in names:
m = re.search('(\d+)x\d+', name)
m = re.search(r'(\d+)x\d+', name)
if m is not None and int(m.group(1)) >= size:
ans = QImage(os.path.join(iconset, name))
if not ans.isNull():

View File

@ -118,7 +118,7 @@ except ImportError:
from htmlentitydefs import name2codepoint
import re
handle_entities = re.compile("&(\w+);").sub
handle_entities = re.compile(r"&(\w+);").sub
def unescape(string):