mirror of
https://github.com/kovidgoyal/calibre.git
synced 2026-04-29 04:00:44 -04:00
string_or_bytes (regex)
isinstance\(([\w\.]+), string_or_bytes\) isinstance(\1, (str, bytes)) replace string_or_bytes used on simple variables/attributs in a isinstance()
This commit is contained in:
parent
f6e012d297
commit
be25741c2b
@ -19,7 +19,7 @@ from importlib.util import decode_source
|
||||
|
||||
from calibre import as_unicode
|
||||
from calibre.customize import InvalidPlugin, Plugin, PluginNotFound, numeric_version, platform
|
||||
from polyglot.builtins import reload, string_or_bytes
|
||||
from polyglot.builtins import reload
|
||||
|
||||
|
||||
def get_resources(zfp, name_or_list_of_names, print_tracebacks_for_missing_resources=True):
|
||||
@ -37,7 +37,7 @@ def get_resources(zfp, name_or_list_of_names, print_tracebacks_for_missing_resou
|
||||
be just the bytes of the resource or None if it wasn't found.
|
||||
'''
|
||||
names = name_or_list_of_names
|
||||
if isinstance(names, string_or_bytes):
|
||||
if isinstance(names, (str, bytes)):
|
||||
names = [names]
|
||||
ans = {}
|
||||
with zipfile.ZipFile(zfp) as zf:
|
||||
@ -74,7 +74,7 @@ def get_icons(zfp, name_or_list_of_names, plugin_name='', print_tracebacks_for_m
|
||||
'''
|
||||
from qt.core import QIcon, QPixmap
|
||||
ans = {}
|
||||
namelist = [name_or_list_of_names] if isinstance(name_or_list_of_names, string_or_bytes) else name_or_list_of_names
|
||||
namelist = [name_or_list_of_names] if isinstance(name_or_list_of_names, (str, bytes)) else name_or_list_of_names
|
||||
failed = set()
|
||||
if plugin_name:
|
||||
for name in namelist:
|
||||
@ -89,7 +89,7 @@ def get_icons(zfp, name_or_list_of_names, plugin_name='', print_tracebacks_for_m
|
||||
from_zfp = get_resources(zfp, list(failed), print_tracebacks_for_missing_resources=print_tracebacks_for_missing_resources)
|
||||
if from_zfp is None:
|
||||
from_zfp = {}
|
||||
elif isinstance(from_zfp, string_or_bytes):
|
||||
elif isinstance(from_zfp, (str, bytes)):
|
||||
from_zfp = {namelist[0]: from_zfp}
|
||||
|
||||
for name in failed:
|
||||
|
||||
@ -72,7 +72,7 @@ from calibre.utils.formatter_functions import compile_user_template_functions, f
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.icu import sort_key
|
||||
from calibre.utils.resources import get_path as P
|
||||
from polyglot.builtins import cmp, itervalues, native_string_type, reraise, string_or_bytes
|
||||
from polyglot.builtins import cmp, itervalues, native_string_type, reraise
|
||||
|
||||
# }}}
|
||||
|
||||
@ -1727,7 +1727,7 @@ class DB:
|
||||
def copy_cover_to(self, path, dest, windows_atomic_move=None, use_hardlink=False, report_file_size=None):
|
||||
path = os.path.abspath(os.path.join(self.library_path, path, COVER_FILE_NAME))
|
||||
if windows_atomic_move is not None:
|
||||
if not isinstance(dest, string_or_bytes):
|
||||
if not isinstance(dest, (str, bytes)):
|
||||
raise Exception('Error, you must pass the dest as a path when'
|
||||
' using windows_atomic_move')
|
||||
if os.access(path, os.R_OK) and dest and not samefile(dest, path):
|
||||
@ -1837,7 +1837,7 @@ class DB:
|
||||
if path is None:
|
||||
return False
|
||||
if windows_atomic_move is not None:
|
||||
if not isinstance(dest, string_or_bytes):
|
||||
if not isinstance(dest, (str, bytes)):
|
||||
raise Exception('Error, you must pass the dest as a path when'
|
||||
' using windows_atomic_move')
|
||||
if dest:
|
||||
@ -2637,7 +2637,7 @@ class DB:
|
||||
|
||||
def set_conversion_options(self, options, fmt):
|
||||
def map_data(x):
|
||||
if not isinstance(x, string_or_bytes):
|
||||
if not isinstance(x, (str, bytes)):
|
||||
x = native_string_type(x)
|
||||
x = x.encode('utf-8') if isinstance(x, str) else x
|
||||
x = pickle_binary_string(x)
|
||||
|
||||
@ -52,7 +52,7 @@ from calibre.utils.filenames import make_long_path_useable
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.icu import sort_key
|
||||
from calibre.utils.localization import canonicalize_lang
|
||||
from polyglot.builtins import cmp, iteritems, itervalues, string_or_bytes
|
||||
from polyglot.builtins import cmp, iteritems, itervalues
|
||||
|
||||
|
||||
class ExtraFile(NamedTuple):
|
||||
@ -1651,7 +1651,7 @@ class Cache:
|
||||
bimap, simap = {}, {}
|
||||
sfield = self.fields[name + '_index']
|
||||
for k, v in book_id_to_val_map.items():
|
||||
if isinstance(v, string_or_bytes):
|
||||
if isinstance(v, (str, bytes)):
|
||||
v, sid = get_series_values(v)
|
||||
else:
|
||||
v = sid = None
|
||||
@ -1882,7 +1882,7 @@ class Cache:
|
||||
# force_changes has no effect on cover manipulation
|
||||
try:
|
||||
cdata = mi.cover_data[1]
|
||||
if cdata is None and isinstance(mi.cover, string_or_bytes) and mi.cover and os.access(mi.cover, os.R_OK):
|
||||
if cdata is None and isinstance(mi.cover, (str, bytes)) and mi.cover and os.access(mi.cover, os.R_OK):
|
||||
with open(mi.cover, 'rb') as f:
|
||||
cdata = f.read() or None
|
||||
if cdata is not None:
|
||||
|
||||
@ -21,7 +21,7 @@ from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.icu import primary_contains, primary_no_punc_contains, sort_key
|
||||
from calibre.utils.localization import canonicalize_lang, lang_map
|
||||
from calibre.utils.search_query_parser import ParseException, SearchQueryParser
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
CONTAINS_MATCH = 0
|
||||
EQUALS_MATCH = 1
|
||||
@ -210,7 +210,7 @@ class DateSearch: # {{{
|
||||
field_count = query.count('/') + 1
|
||||
|
||||
for v, book_ids in field_iter():
|
||||
if isinstance(v, string_or_bytes):
|
||||
if isinstance(v, (str, bytes)):
|
||||
v = parse_date(v)
|
||||
if v is not None and relop(dt_as_local(v), qd, field_count):
|
||||
matches |= book_ids
|
||||
@ -773,7 +773,7 @@ class Parser(SearchQueryParser): # {{{
|
||||
if location in text_fields:
|
||||
for val, book_ids in self.field_iter(location, current_candidates):
|
||||
if val is not None:
|
||||
if isinstance(val, string_or_bytes):
|
||||
if isinstance(val, (str, bytes)):
|
||||
val = (val,)
|
||||
if _match(q, val, matchkind, use_primary_find_in_search=upf, case_sensitive=case_sensitive):
|
||||
matches |= book_ids
|
||||
|
||||
@ -18,7 +18,6 @@ from calibre import as_unicode, prints
|
||||
from calibre.constants import cache_dir, get_windows_number_formats, iswindows, preferred_encoding
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.localization import canonicalize_lang, ngettext
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def force_to_bool(val):
|
||||
@ -48,7 +47,7 @@ def fuzzy_title_patterns():
|
||||
if _fuzzy_title_patterns is None:
|
||||
from calibre.ebooks.metadata import get_title_sort_pat
|
||||
_fuzzy_title_patterns = tuple((re.compile(pat, re.IGNORECASE) if
|
||||
isinstance(pat, string_or_bytes) else pat, repl) for pat, repl in
|
||||
isinstance(pat, (str, bytes)) else pat, repl) for pat, repl in
|
||||
[
|
||||
(r'[\[\](){}<>\'";,:#]', ''),
|
||||
(get_title_sort_pat(), ''),
|
||||
|
||||
@ -8,7 +8,6 @@ import os
|
||||
from calibre import fsync
|
||||
from calibre.devices.usbms.driver import USBMS
|
||||
from calibre.utils.resources import get_image_path as I
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
HTC_BCDS = [0x100, 0x0222, 0x0224, 0x0226, 0x227, 0x228, 0x229, 0x0231, 0x9999]
|
||||
|
||||
@ -286,7 +285,7 @@ class ANDROID(USBMS):
|
||||
opts = [self.EBOOK_DIR_MAIN, '']
|
||||
|
||||
def strtolist(x):
|
||||
if isinstance(x, string_or_bytes):
|
||||
if isinstance(x, (str, bytes)):
|
||||
x = [y.strip() for y in x.split(',')]
|
||||
return x or []
|
||||
|
||||
|
||||
@ -4321,7 +4321,7 @@ class KOBOTOUCH(KOBO):
|
||||
debugging_title = settings.extra_customization[OPT_DEBUGGING_TITLE]
|
||||
start_subclass_extra_options = OPT_DEBUGGING_TITLE + 1
|
||||
|
||||
settings.debugging_title = debugging_title if isinstance(debugging_title, string_or_bytes) else ''
|
||||
settings.debugging_title = debugging_title if isinstance(debugging_title, (str, bytes)) else ''
|
||||
settings.update_device_metadata = settings.update_series
|
||||
settings.extra_customization = settings.extra_customization[start_subclass_extra_options:]
|
||||
|
||||
|
||||
@ -17,7 +17,7 @@ from calibre.ebooks.metadata.book.base import Metadata
|
||||
from calibre.prints import debug_print
|
||||
from calibre.utils.config_base import tweaks
|
||||
from calibre.utils.icu import sort_key
|
||||
from polyglot.builtins import cmp, itervalues, string_or_bytes
|
||||
from polyglot.builtins import cmp, itervalues
|
||||
|
||||
|
||||
def none_cmp(xx, yy):
|
||||
@ -33,7 +33,7 @@ def none_cmp(xx, yy):
|
||||
return 1
|
||||
if y is None:
|
||||
return -1
|
||||
if isinstance(x, string_or_bytes) and isinstance(y, string_or_bytes):
|
||||
if isinstance(x, (str, bytes)) and isinstance(y, (str, bytes)):
|
||||
x, y = sort_key(force_unicode(x)), sort_key(force_unicode(y))
|
||||
try:
|
||||
c = cmp(x, y)
|
||||
|
||||
@ -25,7 +25,6 @@ from calibre.devices.errors import DeviceError
|
||||
from calibre.devices.interface import FAKE_DEVICE_SERIAL, DevicePlugin, ModelMetadata
|
||||
from calibre.devices.usbms.deviceconfig import DeviceConfig
|
||||
from calibre.utils.filenames import ascii_filename as sanitize
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
if ismacos:
|
||||
osx_sanitize_name_pat = re.compile(r'[.-]')
|
||||
@ -965,7 +964,7 @@ class Device(DeviceConfig, DevicePlugin):
|
||||
sanity_check(on_card, files, self.card_prefix(), self.free_space())
|
||||
|
||||
def get_dest_dir(prefix, candidates):
|
||||
if isinstance(candidates, string_or_bytes):
|
||||
if isinstance(candidates, (str, bytes)):
|
||||
candidates = [candidates]
|
||||
if not candidates:
|
||||
candidates = ['']
|
||||
|
||||
@ -20,7 +20,7 @@ from calibre.devices.usbms.cli import CLI
|
||||
from calibre.devices.usbms.device import Device
|
||||
from calibre.ebooks.metadata.book.json_codec import JsonCodec
|
||||
from calibre.prints import debug_print
|
||||
from polyglot.builtins import itervalues, string_or_bytes
|
||||
from polyglot.builtins import itervalues
|
||||
|
||||
|
||||
def safe_walk(top, topdown=True, onerror=None, followlinks=False, maxdepth=128):
|
||||
@ -254,7 +254,7 @@ class USBMS(CLI, Device):
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return changed
|
||||
if isinstance(ebook_dirs, string_or_bytes):
|
||||
if isinstance(ebook_dirs, (str, bytes)):
|
||||
ebook_dirs = [ebook_dirs]
|
||||
for ebook_dir in ebook_dirs:
|
||||
ebook_dir = self.path_to_unicode(ebook_dir)
|
||||
|
||||
@ -27,7 +27,6 @@ from calibre.ebooks.conversion.preprocess import HTMLPreProcessor
|
||||
from calibre.ptempfile import PersistentTemporaryDirectory
|
||||
from calibre.utils.date import parse_date
|
||||
from calibre.utils.zipfile import ZipFile
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
DEBUG_README=b'''
|
||||
This debug folder contains snapshots of the e-book as it passes through the
|
||||
@ -1004,7 +1003,7 @@ OptionRecommendation(name='search_replace',
|
||||
|
||||
def dump_input(self, ret, output_dir):
|
||||
out_dir = os.path.join(self.opts.debug_pipeline, 'input')
|
||||
if isinstance(ret, string_or_bytes):
|
||||
if isinstance(ret, (str, bytes)):
|
||||
shutil.copytree(output_dir, out_dir)
|
||||
else:
|
||||
if not os.path.exists(out_dir):
|
||||
@ -1119,7 +1118,7 @@ OptionRecommendation(name='search_replace',
|
||||
|
||||
if self.opts.transform_html_rules:
|
||||
transform_html_rules = self.opts.transform_html_rules
|
||||
if isinstance(transform_html_rules, string_or_bytes):
|
||||
if isinstance(transform_html_rules, (str, bytes)):
|
||||
transform_html_rules = json.loads(transform_html_rules)
|
||||
from calibre.ebooks.html_transform_rules import transform_conversion_book
|
||||
transform_conversion_book(self.oeb, self.opts, transform_html_rules)
|
||||
@ -1212,7 +1211,7 @@ OptionRecommendation(name='search_replace',
|
||||
transform_css_rules = ()
|
||||
if self.opts.transform_css_rules:
|
||||
transform_css_rules = self.opts.transform_css_rules
|
||||
if isinstance(transform_css_rules, string_or_bytes):
|
||||
if isinstance(transform_css_rules, (str, bytes)):
|
||||
transform_css_rules = json.loads(transform_css_rules)
|
||||
flattener = CSSFlattener(fbase=fbase, fkey=fkey,
|
||||
lineh=line_height,
|
||||
|
||||
@ -43,7 +43,7 @@ from calibre.gui2 import config, ensure_app, load_builtin_fonts, pixmap_to_data
|
||||
from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars
|
||||
from calibre.utils.config import JSONConfig
|
||||
from calibre.utils.resources import get_image_path as I
|
||||
from polyglot.builtins import itervalues, string_or_bytes
|
||||
from polyglot.builtins import itervalues
|
||||
|
||||
# Default settings {{{
|
||||
cprefs = JSONConfig('cover_generation')
|
||||
@ -289,7 +289,7 @@ def format_fields(mi, prefs):
|
||||
|
||||
@contextmanager
|
||||
def preserve_fields(obj, fields):
|
||||
if isinstance(fields, string_or_bytes):
|
||||
if isinstance(fields, (str, bytes)):
|
||||
fields = fields.split()
|
||||
null = object()
|
||||
mem = {f:getattr(obj, f, null) for f in fields}
|
||||
|
||||
@ -20,7 +20,6 @@ from calibre.utils.img import save_cover_data_to
|
||||
from calibre.utils.localization import lang_as_iso639_1
|
||||
from calibre.utils.xml_parse import safe_xml_fromstring
|
||||
from polyglot.binary import as_base64_unicode
|
||||
from polyglot.builtins import string_or_bytes
|
||||
from polyglot.urllib import urlparse
|
||||
|
||||
|
||||
@ -408,9 +407,9 @@ class FB2MLizer:
|
||||
elem = elem_tree
|
||||
|
||||
# Ensure what we are converting is not a string and that the fist tag is part of the XHTML namespace.
|
||||
if not isinstance(elem_tree.tag, string_or_bytes) or namespace(elem_tree.tag) != XHTML_NS:
|
||||
if not isinstance(elem_tree.tag, (str, bytes)) or namespace(elem_tree.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return []
|
||||
|
||||
@ -17,7 +17,7 @@ from calibre import prepare_string_for_xml
|
||||
from calibre.ebooks.oeb.base import OEB_IMAGES, SVG_NS, XHTML, XHTML_NS, XLINK, barename, namespace, rewrite_links, urlnormalize
|
||||
from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from calibre.utils.logging import default_log
|
||||
from polyglot.builtins import as_unicode, string_or_bytes
|
||||
from polyglot.builtins import as_unicode
|
||||
from polyglot.urllib import urldefrag
|
||||
|
||||
SELF_CLOSING_TAGS = {'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta'}
|
||||
@ -104,7 +104,7 @@ class OEB2HTML:
|
||||
for el in root.iter():
|
||||
attribs = el.attrib
|
||||
try:
|
||||
if not isinstance(el.tag, string_or_bytes):
|
||||
if not isinstance(el.tag, (str, bytes)):
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
@ -168,10 +168,10 @@ class OEB2HTMLNoCSSizer(OEB2HTML):
|
||||
'''
|
||||
|
||||
# We can only processes tags. If there isn't a tag return any text.
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) not in (XHTML_NS, SVG_NS):
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) in (XHTML_NS, SVG_NS) \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) in (XHTML_NS, SVG_NS) \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
@ -258,10 +258,10 @@ class OEB2HTMLInlineCSSizer(OEB2HTML):
|
||||
'''
|
||||
|
||||
# We can only processes tags. If there isn't a tag return any text.
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) not in (XHTML_NS, SVG_NS):
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) in (XHTML_NS, SVG_NS) \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) in (XHTML_NS, SVG_NS) \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
@ -362,10 +362,10 @@ class OEB2HTMLClassCSSizer(OEB2HTML):
|
||||
'''
|
||||
|
||||
# We can only processes tags. If there isn't a tag return any text.
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) not in (XHTML_NS, SVG_NS):
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) in (XHTML_NS, SVG_NS) \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) in (XHTML_NS, SVG_NS) \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
|
||||
@ -20,7 +20,7 @@ from calibre.ebooks.lit.maps import HTML_MAP, OPF_MAP
|
||||
from calibre.ebooks.oeb.base import urlnormalize, xpath
|
||||
from calibre.ebooks.oeb.reader import OEBReader
|
||||
from calibre_extensions import lzx, msdes
|
||||
from polyglot.builtins import itervalues, string_or_bytes
|
||||
from polyglot.builtins import itervalues
|
||||
from polyglot.urllib import unquote as urlunquote
|
||||
from polyglot.urllib import urldefrag
|
||||
|
||||
@ -286,7 +286,7 @@ class UnBinary:
|
||||
attr = current_map[oc]
|
||||
elif oc in self.attr_map:
|
||||
attr = self.attr_map[oc]
|
||||
if not attr or not isinstance(attr, string_or_bytes):
|
||||
if not attr or not isinstance(attr, (str, bytes)):
|
||||
raise LitError(
|
||||
f'Unknown attribute {oc} in tag {tag_name}')
|
||||
if attr.startswith('%'):
|
||||
|
||||
@ -26,7 +26,7 @@ from calibre.ebooks.lit.reader import DirectoryEntry
|
||||
from calibre.ebooks.oeb.base import CSS_MIME, OEB_DOCS, OEB_STYLES, OPF_MIME, XHTML_MIME, XML, XML_NS, prefixname, urlnormalize
|
||||
from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from calibre_extensions import msdes
|
||||
from polyglot.builtins import native_string_type, string_or_bytes
|
||||
from polyglot.builtins import native_string_type
|
||||
from polyglot.urllib import unquote, urldefrag
|
||||
|
||||
__all__ = ['LitWriter']
|
||||
@ -173,7 +173,7 @@ class ReBinary:
|
||||
|
||||
def tree_to_binary(self, elem, nsrmap=NSRMAP, parents=[],
|
||||
inhead=False, preserve=False):
|
||||
if not isinstance(elem.tag, string_or_bytes):
|
||||
if not isinstance(elem.tag, (str, bytes)):
|
||||
# Don't emit any comments or raw entities
|
||||
return
|
||||
nsrmap = copy.copy(nsrmap)
|
||||
|
||||
@ -7,7 +7,7 @@ import sys
|
||||
|
||||
from calibre.ebooks.lrf.fonts import get_font
|
||||
from calibre.ebooks.lrf.pylrs.pylrs import CR, CharButton, LrsTextTag, Paragraph, Plot, Span, Text, TextBlock
|
||||
from polyglot.builtins import native_string_type, string_or_bytes
|
||||
from polyglot.builtins import native_string_type
|
||||
|
||||
|
||||
def ceil(num):
|
||||
@ -39,7 +39,7 @@ def tokens(tb):
|
||||
yield 2, None
|
||||
elif isinstance(x, Text):
|
||||
yield x.text, cattrs(attrs, {})
|
||||
elif isinstance(x, string_or_bytes):
|
||||
elif isinstance(x, (str, bytes)):
|
||||
yield x, cattrs(attrs, {})
|
||||
elif isinstance(x, (CharButton, LrsTextTag)):
|
||||
if x.contents:
|
||||
|
||||
@ -42,7 +42,6 @@ from calibre.ebooks.lrf.pylrs.pylrs import (
|
||||
TextStyle,
|
||||
)
|
||||
from calibre.utils.config import OptionParser
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class LrsParser:
|
||||
@ -113,7 +112,7 @@ class LrsParser:
|
||||
if isinstance(contents[0], NavigableString):
|
||||
contents[0] = contents[0].string.lstrip()
|
||||
for item in contents:
|
||||
if isinstance(item, string_or_bytes):
|
||||
if isinstance(item, (str, bytes)):
|
||||
p.append(item)
|
||||
elif isinstance(item, NavigableString):
|
||||
p.append(item.string)
|
||||
|
||||
@ -24,7 +24,6 @@ from shutil import copyfileobj
|
||||
from calibre.ebooks.chardet import xml_to_unicode
|
||||
from calibre.ebooks.metadata import MetaInformation, string_to_authors
|
||||
from calibre.utils.cleantext import clean_xml_chars
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
BYTE = '<B' #: Unsigned char little endian encoded in 1 byte
|
||||
WORD = '<H' #: Unsigned short little endian encoded in 2 bytes
|
||||
@ -98,7 +97,7 @@ class fixed_stringfield:
|
||||
return obj.unpack(start=self._start, fmt='<'+length+'s')[0]
|
||||
|
||||
def __set__(self, obj, val):
|
||||
if not isinstance(val, string_or_bytes):
|
||||
if not isinstance(val, (str, bytes)):
|
||||
val = str(val)
|
||||
if isinstance(val, str):
|
||||
val = val.encode('utf-8')
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
''' elements.py -- replacements and helpers for ElementTree '''
|
||||
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class ElementWriter:
|
||||
|
||||
@ -24,7 +22,7 @@ class ElementWriter:
|
||||
|
||||
def _writeAttribute(self, f, name, value):
|
||||
f.write(f' {name!s}="')
|
||||
if not isinstance(value, string_or_bytes):
|
||||
if not isinstance(value, (str, bytes)):
|
||||
value = str(value)
|
||||
value = self._encodeCdata(value)
|
||||
value = value.replace('"', '"')
|
||||
|
||||
@ -11,8 +11,6 @@ import os
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
from .pylrfopt import tagListOptimizer
|
||||
|
||||
PYLRF_VERSION = '1.0'
|
||||
@ -400,7 +398,7 @@ class LrfTag:
|
||||
for f in self.format:
|
||||
if isinstance(f, dict):
|
||||
p = f[p]
|
||||
elif isinstance(f, string_or_bytes):
|
||||
elif isinstance(f, (str, bytes)):
|
||||
if isinstance(p, tuple):
|
||||
writeString(lrf, struct.pack(f, *p))
|
||||
else:
|
||||
|
||||
@ -66,7 +66,7 @@ DEFAULT_SOURCE_ENCODING = 'cp1252' # default is us-windows character set
|
||||
DEFAULT_GENREADING = 'fs' # default is yes to both lrf and lrs
|
||||
|
||||
from calibre import __appname__, __version__, replace_entities
|
||||
from polyglot.builtins import iteritems, native_string_type, string_or_bytes
|
||||
from polyglot.builtins import iteritems, native_string_type
|
||||
|
||||
|
||||
class LrsError(Exception):
|
||||
@ -105,7 +105,7 @@ def ElementWithReading(tag, text, reading=False):
|
||||
|
||||
if text is None:
|
||||
readingText = ''
|
||||
elif isinstance(text, string_or_bytes):
|
||||
elif isinstance(text, (str, bytes)):
|
||||
readingText = text
|
||||
else:
|
||||
# assumed to be a sequence of (name, sortas)
|
||||
@ -161,7 +161,7 @@ class Delegator:
|
||||
setattr(self, m, getattr(d, m))
|
||||
|
||||
# for setting in d.getSettings():
|
||||
# if isinstance(setting, string_or_bytes):
|
||||
# if isinstance(setting, (str, bytes)):
|
||||
# setting = (d, setting)
|
||||
# delegates = \
|
||||
# self.delegatedSettingsDict.setdefault(setting[1], [])
|
||||
@ -292,7 +292,7 @@ class LrsContainer:
|
||||
else:
|
||||
raise LrsError(f"can't append {content.__class__.__name__} to {self.__class__.__name__}")
|
||||
|
||||
if convertText and isinstance(content, string_or_bytes):
|
||||
if convertText and isinstance(content, (str, bytes)):
|
||||
content = Text(content)
|
||||
|
||||
content.setParent(self)
|
||||
@ -585,14 +585,14 @@ class Book(Delegator):
|
||||
ts.attrs['baselineskip'] = rescale(ts.attrs['baselineskip'])
|
||||
|
||||
def renderLrs(self, lrsFile, encoding='UTF-8'):
|
||||
if isinstance(lrsFile, string_or_bytes):
|
||||
if isinstance(lrsFile, (str, bytes)):
|
||||
lrsFile = codecs.open(lrsFile, 'wb', encoding=encoding)
|
||||
self.render(lrsFile, outputEncodingName=encoding)
|
||||
lrsFile.close()
|
||||
|
||||
def renderLrf(self, lrfFile):
|
||||
self.appendReferencedObjects(self)
|
||||
if isinstance(lrfFile, string_or_bytes):
|
||||
if isinstance(lrfFile, (str, bytes)):
|
||||
lrfFile = open(lrfFile, 'wb')
|
||||
lrfWriter = LrfWriter(self.sourceencoding)
|
||||
|
||||
@ -1489,7 +1489,7 @@ class Paragraph(LrsContainer):
|
||||
LrsContainer.__init__(self, [Text, CR, DropCaps, CharButton,
|
||||
LrsSimpleChar1, bytes, str])
|
||||
if text is not None:
|
||||
if isinstance(text, string_or_bytes):
|
||||
if isinstance(text, (str, bytes)):
|
||||
text = Text(text)
|
||||
self.append(text)
|
||||
|
||||
@ -1808,7 +1808,7 @@ class Span(LrsSimpleChar1, LrsContainer):
|
||||
def __init__(self, text=None, **attrs):
|
||||
LrsContainer.__init__(self, [LrsSimpleChar1, Text, bytes, str])
|
||||
if text is not None:
|
||||
if isinstance(text, string_or_bytes):
|
||||
if isinstance(text, (str, bytes)):
|
||||
text = Text(text)
|
||||
self.append(text)
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ from calibre.library.field_metadata import FieldMetadata
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.icu import sort_key
|
||||
from calibre.utils.localization import ngettext
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
# Special sets used to optimize the performance of getting and setting
|
||||
# attributes on Metadata objects
|
||||
@ -588,7 +588,7 @@ class Metadata:
|
||||
meta = other.get_user_metadata(x, make_copy=True)
|
||||
if meta is not None:
|
||||
self_tags = self.get(x, [])
|
||||
if isinstance(self_tags, string_or_bytes):
|
||||
if isinstance(self_tags, (str, bytes)):
|
||||
self_tags = []
|
||||
self.set_user_metadata(x, meta) # get... did the deepcopy
|
||||
other_tags = other.get(x, [])
|
||||
|
||||
@ -10,7 +10,7 @@ import re
|
||||
|
||||
from calibre import force_unicode
|
||||
from calibre.ebooks.metadata import MetaInformation
|
||||
from polyglot.builtins import int_to_byte, string_or_bytes
|
||||
from polyglot.builtins import int_to_byte
|
||||
|
||||
title_pat = re.compile(br'\{\\info.*?\{\\title(.*?)(?<!\\)\}', re.DOTALL)
|
||||
author_pat = re.compile(br'\{\\info.*?\{\\author(.*?)(?<!\\)\}', re.DOTALL)
|
||||
@ -159,7 +159,7 @@ def create_metadata(stream, options):
|
||||
md.append(rf'{{\title {title}}}')
|
||||
if options.authors:
|
||||
au = options.authors
|
||||
if not isinstance(au, string_or_bytes):
|
||||
if not isinstance(au, (str, bytes)):
|
||||
au = ', '.join(au)
|
||||
author = encode(au)
|
||||
md.append(rf'{{\author {author}}}')
|
||||
|
||||
@ -21,7 +21,7 @@ from calibre.ebooks.metadata.opf2 import dump_dict
|
||||
from calibre.utils.date import isoformat, now, parse_date
|
||||
from calibre.utils.localization import canonicalize_lang, lang_as_iso639_1
|
||||
from calibre.utils.xml_parse import safe_xml_fromstring
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
_xml_declaration = re.compile(r'<\?xml[^<>]+encoding\s*=\s*[\'"](.*?)[\'"][^<>]*>', re.IGNORECASE)
|
||||
|
||||
@ -489,7 +489,7 @@ def metadata_to_xmp_packet(mi):
|
||||
'authors':('dc:creator', True), 'tags':('dc:subject', False), 'publisher':('dc:publisher', False),
|
||||
}):
|
||||
val = mi.get(prop) or ()
|
||||
if isinstance(val, string_or_bytes):
|
||||
if isinstance(val, (str, bytes)):
|
||||
val = [val]
|
||||
create_sequence_property(dc, tag, val, ordered)
|
||||
if not mi.is_null('pubdate'):
|
||||
|
||||
@ -17,7 +17,6 @@ from calibre.ebooks.oeb.base import XHTML, XHTML_NS, barename, namespace, urlnor
|
||||
from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from calibre.ebooks.oeb.transforms.flatcss import KeyMapper
|
||||
from calibre.utils.imghdr import identify
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
MBP_NS = 'http://mobipocket.com/ns/mbp'
|
||||
|
||||
@ -156,7 +155,7 @@ class MobiMLizer:
|
||||
return self.fnums[self.fmap[ptsize]]
|
||||
|
||||
def mobimlize_measure(self, ptsize):
|
||||
if isinstance(ptsize, string_or_bytes):
|
||||
if isinstance(ptsize, (str, bytes)):
|
||||
return ptsize
|
||||
embase = self.profile.fbase
|
||||
if round(ptsize) < embase:
|
||||
@ -199,7 +198,7 @@ class MobiMLizer:
|
||||
parent = bstate.nested[-1] if bstate.nested else bstate.body
|
||||
indent = istate.indent
|
||||
left = istate.left
|
||||
if isinstance(indent, string_or_bytes):
|
||||
if isinstance(indent, (str, bytes)):
|
||||
indent = 0
|
||||
if indent < 0 and abs(indent) < left:
|
||||
left += indent
|
||||
@ -320,7 +319,7 @@ class MobiMLizer:
|
||||
inline = bstate.inline
|
||||
content = self.preize_text(text, pre_wrap=istate.pre_wrap) if istate.preserve or istate.pre_wrap else [text]
|
||||
for item in content:
|
||||
if isinstance(item, string_or_bytes):
|
||||
if isinstance(item, (str, bytes)):
|
||||
if len(inline) == 0:
|
||||
inline.text = (inline.text or '') + item
|
||||
else:
|
||||
@ -331,7 +330,7 @@ class MobiMLizer:
|
||||
|
||||
def mobimlize_elem(self, elem, stylizer, bstate, istates,
|
||||
ignore_valign=False):
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) != XHTML_NS:
|
||||
return
|
||||
style = stylizer.style(elem)
|
||||
|
||||
@ -14,7 +14,6 @@ from io import BytesIO
|
||||
from calibre.ebooks.mobi.mobiml import MBP_NS
|
||||
from calibre.ebooks.mobi.utils import is_guide_ref_start
|
||||
from calibre.ebooks.oeb.base import OEB_DOCS, XHTML, XHTML_NS, XML_NS, namespace, prefixname, urlnormalize
|
||||
from polyglot.builtins import string_or_bytes
|
||||
from polyglot.urllib import urldefrag
|
||||
|
||||
|
||||
@ -307,7 +306,7 @@ class Serializer:
|
||||
|
||||
def serialize_elem(self, elem, item, nsrmap=NSRMAP):
|
||||
buf = self.buf
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) not in nsrmap:
|
||||
return
|
||||
tag = prefixname(elem.tag, nsrmap)
|
||||
|
||||
@ -20,7 +20,7 @@ from odf.opendocument import load as odLoad
|
||||
from calibre import CurrentDir, walk
|
||||
from calibre.ebooks.oeb.base import _css_logger
|
||||
from calibre.utils.xml_parse import safe_xml_fromstring
|
||||
from polyglot.builtins import as_bytes, string_or_bytes
|
||||
from polyglot.builtins import as_bytes
|
||||
|
||||
|
||||
class Extract(ODF2XHTML):
|
||||
@ -250,7 +250,7 @@ class Extract(ODF2XHTML):
|
||||
# first load the odf structure
|
||||
self.lines = []
|
||||
self._wfunc = self._wlines
|
||||
if isinstance(odffile, string_or_bytes) \
|
||||
if isinstance(odffile, (str, bytes)) \
|
||||
or hasattr(odffile, 'read'): # Added by Kovid
|
||||
self.document = odLoad(odffile)
|
||||
else:
|
||||
|
||||
@ -30,7 +30,7 @@ from calibre.utils.icu import title_case as icu_title
|
||||
from calibre.utils.localization import __, is_rtl_lang
|
||||
from calibre.utils.short_uuid import uuid4
|
||||
from calibre.utils.xml_parse import safe_xml_fromstring
|
||||
from polyglot.builtins import iteritems, itervalues, string_or_bytes
|
||||
from polyglot.builtins import iteritems, itervalues
|
||||
from polyglot.urllib import unquote as urlunquote
|
||||
from polyglot.urllib import urldefrag, urljoin, urlparse, urlunparse
|
||||
|
||||
@ -1051,7 +1051,7 @@ class Manifest:
|
||||
mt = self.media_type.lower()
|
||||
except Exception:
|
||||
mt = 'application/octet-stream'
|
||||
if not isinstance(data, string_or_bytes):
|
||||
if not isinstance(data, (str, bytes)):
|
||||
pass # already parsed
|
||||
elif mt in OEB_DOCS:
|
||||
data = self._parse_xhtml(data)
|
||||
@ -1306,7 +1306,7 @@ class Spine:
|
||||
self.page_progression_direction = None
|
||||
|
||||
def _linear(self, linear):
|
||||
if isinstance(linear, string_or_bytes):
|
||||
if isinstance(linear, (str, bytes)):
|
||||
linear = linear.lower()
|
||||
if linear is None or linear in ('yes', 'true'):
|
||||
linear = True
|
||||
|
||||
@ -13,7 +13,7 @@ from calibre import force_unicode, xml_replace_entities
|
||||
from calibre.constants import filesystem_encoding
|
||||
from calibre.ebooks.chardet import strip_encoding_declarations, xml_to_unicode
|
||||
from calibre.utils.xml_parse import safe_html_fromstring, safe_xml_fromstring
|
||||
from polyglot.builtins import iteritems, itervalues, string_or_bytes
|
||||
from polyglot.builtins import iteritems, itervalues
|
||||
|
||||
XHTML_NS = 'http://www.w3.org/1999/xhtml'
|
||||
XMLNS_NS = 'http://www.w3.org/2000/xmlns/'
|
||||
@ -101,7 +101,7 @@ def html5_parse(data, max_nesting_depth=100):
|
||||
# Check that the asinine HTML 5 algorithm did not result in a tree with
|
||||
# insane nesting depths
|
||||
for x in data.iterdescendants():
|
||||
if isinstance(x.tag, string_or_bytes) and not len(x): # Leaf node
|
||||
if isinstance(x.tag, (str, bytes)) and not len(x): # Leaf node
|
||||
depth = node_depth(x)
|
||||
if depth > max_nesting_depth:
|
||||
raise ValueError(f'HTML 5 parsing resulted in a tree with nesting depth > {max_nesting_depth}')
|
||||
@ -297,7 +297,7 @@ def parse_html(data, log=None, decoder=None, preprocessor=None,
|
||||
nroot = etree.Element(XHTML('html'),
|
||||
nsmap={None: XHTML_NS}, attrib=attrib)
|
||||
for elem in data.iterdescendants():
|
||||
if isinstance(elem.tag, string_or_bytes) and \
|
||||
if isinstance(elem.tag, (str, bytes)) and \
|
||||
namespace(elem.tag) == ns:
|
||||
elem.tag = XHTML(barename(elem.tag))
|
||||
for elem in data:
|
||||
|
||||
@ -13,14 +13,14 @@ from calibre import prints
|
||||
from calibre.ebooks.oeb.base import XHTML
|
||||
from calibre.utils.filenames import ascii_filename
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from polyglot.builtins import itervalues, string_or_bytes
|
||||
from polyglot.builtins import itervalues
|
||||
|
||||
props = {'font-family':None, 'font-weight':'normal', 'font-style':'normal', 'font-stretch':'normal'}
|
||||
|
||||
|
||||
def matching_rule(font, rules):
|
||||
ff = font['font-family']
|
||||
if not isinstance(ff, string_or_bytes):
|
||||
if not isinstance(ff, (str, bytes)):
|
||||
ff = tuple(ff)[0]
|
||||
family = icu_lower(ff)
|
||||
wt = font['font-weight']
|
||||
@ -30,7 +30,7 @@ def matching_rule(font, rules):
|
||||
for rule in rules:
|
||||
if rule['font-style'] == style and rule['font-stretch'] == stretch and rule['font-weight'] == wt:
|
||||
ff = rule['font-family']
|
||||
if not isinstance(ff, string_or_bytes):
|
||||
if not isinstance(ff, (str, bytes)):
|
||||
ff = tuple(ff)[0]
|
||||
if icu_lower(ff) == family:
|
||||
return rule
|
||||
@ -161,7 +161,7 @@ def do_embed(container, font, report):
|
||||
def embed_font(container, font, all_font_rules, report, warned):
|
||||
rule = matching_rule(font, all_font_rules)
|
||||
ff = font['font-family']
|
||||
if not isinstance(ff, string_or_bytes):
|
||||
if not isinstance(ff, (str, bytes)):
|
||||
ff = ff[0]
|
||||
if rule is None:
|
||||
from calibre.utils.fonts.scanner import NoFonts, font_scanner
|
||||
|
||||
@ -12,7 +12,6 @@ from calibre.ebooks.oeb.base import OEB_DOCS, OPF, XHTML, XPNSMAP, XPath, barena
|
||||
from calibre.ebooks.oeb.polish.errors import MalformedMarkup
|
||||
from calibre.ebooks.oeb.polish.replace import LinkRebaser
|
||||
from calibre.ebooks.oeb.polish.toc import node_from_loc
|
||||
from polyglot.builtins import string_or_bytes
|
||||
from polyglot.urllib import urlparse
|
||||
|
||||
|
||||
@ -396,9 +395,9 @@ def merge_html(container, names, master, insert_page_breaks=False):
|
||||
|
||||
first_child = ''
|
||||
for first_child in children:
|
||||
if not isinstance(first_child, string_or_bytes):
|
||||
if not isinstance(first_child, (str, bytes)):
|
||||
break
|
||||
if isinstance(first_child, string_or_bytes):
|
||||
if isinstance(first_child, (str, bytes)):
|
||||
# body contained only text, no tags
|
||||
first_child = body.makeelement(XHTML('p'))
|
||||
first_child.text, children[0] = children[0], first_child
|
||||
@ -434,7 +433,7 @@ def merge_html(container, names, master, insert_page_breaks=False):
|
||||
a.set('href', '#' + amap[q])
|
||||
|
||||
for child in children:
|
||||
if isinstance(child, string_or_bytes):
|
||||
if isinstance(child, (str, bytes)):
|
||||
add_text(master_body, child)
|
||||
else:
|
||||
master_body.append(copy.deepcopy(child))
|
||||
|
||||
@ -23,7 +23,7 @@ from calibre.ebooks.oeb.base import CSS_MIME, OEB_STYLES, SVG, SVG_NS, XHTML, XH
|
||||
from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from calibre.utils.filenames import ascii_filename, ascii_text
|
||||
from calibre.utils.icu import numeric_sort_key
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
COLLAPSE = re.compile(r'[ \t\r\n\v]+')
|
||||
STRIPNUM = re.compile(r'[-0-9]+$')
|
||||
@ -361,7 +361,7 @@ class CSSFlattener:
|
||||
cssdict[property] = f'{value/fsize:0.5f}em'
|
||||
|
||||
def flatten_node(self, node, stylizer, names, styles, pseudo_styles, psize, item_id, recurse=True):
|
||||
if not isinstance(node.tag, string_or_bytes) or namespace(node.tag) not in (XHTML_NS, SVG_NS):
|
||||
if not isinstance(node.tag, (str, bytes)) or namespace(node.tag) not in (XHTML_NS, SVG_NS):
|
||||
return
|
||||
tag = barename(node.tag)
|
||||
style = stylizer.style(node)
|
||||
|
||||
@ -12,7 +12,6 @@ from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.icu import title_case as icu_title
|
||||
from calibre.utils.icu import upper as icu_upper
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
CASE_MANGLER_CSS = '''
|
||||
.calibre_lowercase {
|
||||
@ -97,7 +96,7 @@ class CaseMangler:
|
||||
last = child
|
||||
|
||||
def mangle_elem(self, elem, stylizer):
|
||||
if not isinstance(elem.tag, string_or_bytes) or \
|
||||
if not isinstance(elem.tag, (str, bytes)) or \
|
||||
namespace(elem.tag) != XHTML_NS:
|
||||
return
|
||||
children = list(elem)
|
||||
|
||||
@ -13,7 +13,6 @@ from lxml import etree
|
||||
from calibre.ebooks.pdb.ereader import image_name
|
||||
from calibre.ebooks.pml import unipmlcode
|
||||
from calibre.utils.xml_parse import safe_xml_fromstring
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
TAG_MAP = {
|
||||
'b' : 'B',
|
||||
@ -223,9 +222,9 @@ class PMLMLizer:
|
||||
def dump_text(self, elem, stylizer, page, tag_stack=[]):
|
||||
from calibre.ebooks.oeb.base import XHTML_NS, barename, namespace
|
||||
|
||||
if not isinstance(elem.tag, string_or_bytes) or namespace(elem.tag) != XHTML_NS:
|
||||
if not isinstance(elem.tag, (str, bytes)) or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return []
|
||||
|
||||
@ -10,7 +10,6 @@ import re
|
||||
|
||||
from calibre import prepare_string_for_xml
|
||||
from calibre.ebooks.rb import unique_name
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
TAGS = [
|
||||
'b',
|
||||
@ -141,9 +140,9 @@ class RBMLizer:
|
||||
def dump_text(self, elem, stylizer, page, tag_stack=[]):
|
||||
from calibre.ebooks.oeb.base import XHTML_NS, barename, namespace
|
||||
|
||||
if not isinstance(elem.tag, string_or_bytes) or namespace(elem.tag) != XHTML_NS:
|
||||
if not isinstance(elem.tag, (str, bytes)) or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
|
||||
@ -16,7 +16,6 @@ from lxml import etree
|
||||
from calibre.ebooks.metadata import authors_to_string
|
||||
from calibre.utils.img import save_cover_data_to
|
||||
from calibre.utils.imghdr import identify
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
TAGS = {
|
||||
'b': '\\b',
|
||||
@ -213,10 +212,10 @@ class RTFMLizer:
|
||||
def dump_text(self, elem, stylizer, tag_stack=[]):
|
||||
from calibre.ebooks.oeb.base import XHTML_NS, barename, namespace, urlnormalize
|
||||
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return elem.tail
|
||||
return ''
|
||||
|
||||
@ -11,8 +11,6 @@ import re
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def ProcessFileName(fileName):
|
||||
# Flat the path
|
||||
@ -211,10 +209,10 @@ class SNBMLizer:
|
||||
def dump_text(self, subitems, elem, stylizer, end='', pre=False, li=''):
|
||||
from calibre.ebooks.oeb.base import XHTML_NS, barename, namespace
|
||||
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
|
||||
@ -12,7 +12,6 @@ from functools import partial
|
||||
from calibre.ebooks.htmlz.oeb2html import OEB2HTML
|
||||
from calibre.ebooks.oeb.base import XHTML, XHTML_NS, barename, namespace, rewrite_links
|
||||
from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class MarkdownMLizer(OEB2HTML):
|
||||
@ -108,10 +107,10 @@ class MarkdownMLizer(OEB2HTML):
|
||||
'''
|
||||
|
||||
# We can only processes tags. If there isn't a tag return any text.
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
|
||||
@ -13,7 +13,6 @@ from calibre.ebooks.htmlz.oeb2html import OEB2HTML
|
||||
from calibre.ebooks.oeb.base import XHTML, XHTML_NS, barename, namespace, rewrite_links
|
||||
from calibre.ebooks.oeb.stylizer import Stylizer
|
||||
from calibre.ebooks.textile.unsmarten import unsmarten
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class TextileMLizer(OEB2HTML):
|
||||
@ -231,10 +230,10 @@ class TextileMLizer(OEB2HTML):
|
||||
'''
|
||||
|
||||
# We can only processes tags. If there isn't a tag return any text.
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
|
||||
@ -10,8 +10,6 @@ import re
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
BLOCK_TAGS = [
|
||||
'div',
|
||||
'p',
|
||||
@ -189,10 +187,10 @@ class TXTMLizer:
|
||||
'''
|
||||
from calibre.ebooks.oeb.base import XHTML_NS, barename, namespace
|
||||
|
||||
if not isinstance(elem.tag, string_or_bytes) \
|
||||
if not isinstance(elem.tag, (str, bytes)) \
|
||||
or namespace(elem.tag) != XHTML_NS:
|
||||
p = elem.getparent()
|
||||
if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) == XHTML_NS \
|
||||
if p is not None and isinstance(p.tag, (str, bytes)) and namespace(p.tag) == XHTML_NS \
|
||||
and elem.tail:
|
||||
return [elem.tail]
|
||||
return ['']
|
||||
|
||||
@ -91,7 +91,7 @@ from calibre.utils.resources import get_image_path as I
|
||||
from calibre.utils.resources import get_path as P
|
||||
from calibre.utils.resources import user_dir
|
||||
from polyglot import queue
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
del pqc, geometry_for_restore_as_dict
|
||||
NO_URL_FORMATTING = QUrl.UrlFormattingOption.None_
|
||||
@ -1487,7 +1487,7 @@ SanitizeLibraryPath = sanitize_env_vars # For old plugins
|
||||
|
||||
|
||||
def open_url(qurl):
|
||||
if isinstance(qurl, string_or_bytes):
|
||||
if isinstance(qurl, (str, bytes)):
|
||||
qurl = QUrl(qurl)
|
||||
scheme = qurl.scheme().lower() or 'file'
|
||||
import fnmatch
|
||||
@ -1533,7 +1533,7 @@ def open_url(qurl):
|
||||
|
||||
|
||||
def safe_open_url(qurl):
|
||||
if isinstance(qurl, string_or_bytes):
|
||||
if isinstance(qurl, (str, bytes)):
|
||||
qurl = QUrl(qurl)
|
||||
if qurl.scheme() in ('', 'file'):
|
||||
path = qurl.toLocalFile()
|
||||
|
||||
@ -14,7 +14,6 @@ from calibre import prints
|
||||
from calibre.constants import ismacos
|
||||
from calibre.gui2 import Dispatcher
|
||||
from calibre.gui2.keyboard import NameConflict
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def toolbar_widgets_for_action(gui, action):
|
||||
@ -244,7 +243,7 @@ class InterfaceAction(QObject):
|
||||
if attr == 'qaction':
|
||||
shortcut_action = ma
|
||||
if shortcut is not None:
|
||||
keys = ((shortcut,) if isinstance(shortcut, string_or_bytes) else
|
||||
keys = ((shortcut,) if isinstance(shortcut, (str, bytes)) else
|
||||
tuple(shortcut))
|
||||
if shortcut_name is None:
|
||||
if self.action_shortcut_name is not None:
|
||||
@ -324,7 +323,7 @@ class InterfaceAction(QObject):
|
||||
ac.setIcon(icon)
|
||||
keys = ()
|
||||
if shortcut is not None and shortcut is not False:
|
||||
keys = ((shortcut,) if isinstance(shortcut, string_or_bytes) else
|
||||
keys = ((shortcut,) if isinstance(shortcut, (str, bytes)) else
|
||||
tuple(shortcut))
|
||||
unique_name = menu_action_unique_name(self, unique_name)
|
||||
if description is not None:
|
||||
|
||||
@ -25,7 +25,6 @@ from calibre.utils.config_base import tweaks
|
||||
from calibre.utils.filenames import ascii_filename, make_long_path_useable
|
||||
from calibre.utils.icu import sort_key
|
||||
from calibre.utils.localization import ngettext
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def get_filters():
|
||||
@ -541,7 +540,7 @@ class AddAction(InterfaceAction):
|
||||
self._add_extra_files({cid}, add_as_data_files)
|
||||
|
||||
def __add_filesystem_book(self, paths, allow_device=True):
|
||||
if isinstance(paths, string_or_bytes):
|
||||
if isinstance(paths, (str, bytes)):
|
||||
paths = [paths]
|
||||
books = [path for path in map(os.path.abspath, paths) if os.access(path,
|
||||
os.R_OK)]
|
||||
@ -696,7 +695,7 @@ class AddAction(InterfaceAction):
|
||||
self.gui.device_job_exception(job)
|
||||
return
|
||||
paths = job.result
|
||||
ok_paths = [x for x in paths if isinstance(x, string_or_bytes)]
|
||||
ok_paths = [x for x in paths if isinstance(x, (str, bytes))]
|
||||
failed_paths = [x for x in paths if isinstance(x, tuple)]
|
||||
if failed_paths:
|
||||
if not ok_paths:
|
||||
|
||||
@ -11,7 +11,6 @@ from qt.core import QToolButton
|
||||
from calibre.gui2.actions import InterfaceAction
|
||||
from calibre.startup import connect_lambda
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class SimilarBooksAction(InterfaceAction):
|
||||
@ -83,7 +82,7 @@ class SimilarBooksAction(InterfaceAction):
|
||||
if not val:
|
||||
return
|
||||
|
||||
if isinstance(val, string_or_bytes):
|
||||
if isinstance(val, (str, bytes)):
|
||||
val = [val]
|
||||
if typ == 'authors':
|
||||
import re
|
||||
|
||||
@ -35,12 +35,11 @@ from calibre.utils.filenames import make_long_path_useable
|
||||
from calibre.utils.icu import lower as icu_lower
|
||||
from calibre.utils.ipc.pool import Failure, Pool
|
||||
from calibre.utils.localization import ngettext
|
||||
from polyglot.builtins import string_or_bytes
|
||||
from polyglot.queue import Empty
|
||||
|
||||
|
||||
def validate_source(source, parent=None): # {{{
|
||||
if isinstance(source, string_or_bytes):
|
||||
if isinstance(source, (str, bytes)):
|
||||
if not os.path.exists(source):
|
||||
error_dialog(parent, _('Cannot add books'), _(
|
||||
'The path %s does not exist') % source, show=True)
|
||||
@ -210,7 +209,7 @@ class Adder(QObject):
|
||||
return tdir
|
||||
|
||||
try:
|
||||
if isinstance(self.source, string_or_bytes):
|
||||
if isinstance(self.source, (str, bytes)):
|
||||
find_files(self.source)
|
||||
self.ignore_opf = True
|
||||
else:
|
||||
|
||||
@ -17,7 +17,7 @@ from calibre.gui2.threaded_jobs import ThreadedJob
|
||||
from calibre.ptempfile import PersistentTemporaryDirectory
|
||||
from calibre.utils.filenames import ascii_filename
|
||||
from calibre.web import get_download_filename_from_response
|
||||
from polyglot.builtins import as_unicode, string_or_bytes
|
||||
from polyglot.builtins import as_unicode
|
||||
|
||||
|
||||
class DownloadInfo(MessageBox):
|
||||
@ -157,7 +157,7 @@ class EbookDownloadMixin:
|
||||
|
||||
def download_ebook(self, url='', cookie_file=None, filename='', save_loc='', add_to_lib=True, tags=[], create_browser=None):
|
||||
if tags:
|
||||
if isinstance(tags, string_or_bytes):
|
||||
if isinstance(tags, (str, bytes)):
|
||||
tags = tags.split(',')
|
||||
start_ebook_download(Dispatcher(self.downloaded_ebook), self.job_manager, self, cookie_file, url, filename, save_loc, add_to_lib, tags, create_browser)
|
||||
self.status_bar.show_message(_('Downloading') + ' ' + as_unicode(filename or url, errors='replace'), 3000)
|
||||
|
||||
@ -49,7 +49,7 @@ from calibre.utils.icu import sort_key
|
||||
from calibre.utils.localization import calibre_langcode_to_name, ngettext
|
||||
from calibre.utils.resources import get_path as P
|
||||
from calibre.utils.search_query_parser import ParseException, SearchQueryParser
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
Counts = namedtuple('Counts', 'library_total total current')
|
||||
|
||||
@ -1481,7 +1481,7 @@ class OnDeviceSearch(SearchQueryParser): # {{{
|
||||
vals = accessor(row)
|
||||
if vals is None:
|
||||
vals = ''
|
||||
if isinstance(vals, string_or_bytes):
|
||||
if isinstance(vals, (str, bytes)):
|
||||
vals = vals.split(',') if locvalue == 'collections' else [vals]
|
||||
if _match(query, vals, m, use_primary_find_in_search=upf):
|
||||
matches.add(index)
|
||||
|
||||
@ -13,7 +13,7 @@ from qt.core import QEventLoop
|
||||
from calibre import force_unicode
|
||||
from calibre.constants import DEBUG, filesystem_encoding, preferred_encoding
|
||||
from calibre.utils.config import dynamic
|
||||
from polyglot.builtins import reraise, string_or_bytes
|
||||
from polyglot.builtins import reraise
|
||||
|
||||
|
||||
def dialog_name(name, title):
|
||||
@ -78,7 +78,7 @@ def get_initial_dir(name, title, default_dir, no_save_dir):
|
||||
return ensure_dir(process_path(default_dir))
|
||||
key = dialog_name(name, title)
|
||||
saved = dynamic.get(key)
|
||||
if not isinstance(saved, string_or_bytes):
|
||||
if not isinstance(saved, (str, bytes)):
|
||||
saved = None
|
||||
if saved and os.path.isdir(saved):
|
||||
return ensure_dir(process_path(saved))
|
||||
|
||||
@ -12,7 +12,6 @@ from qt.core import QBrush, QColor, QFont, QFontMetrics, QGraphicsItem, QGraphic
|
||||
|
||||
from calibre.ebooks.hyphenate import hyphenate_word
|
||||
from calibre.ebooks.lrf.fonts import LIBERATION_FONT_MAP
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def WEIGHT_MAP(wt):
|
||||
@ -241,7 +240,7 @@ class TextBlock:
|
||||
open_containers = collections.deque()
|
||||
self.in_para = False
|
||||
for i in tb.content:
|
||||
if isinstance(i, string_or_bytes):
|
||||
if isinstance(i, (str, bytes)):
|
||||
self.process_text(i)
|
||||
elif i is None:
|
||||
if len(open_containers) > 0:
|
||||
|
||||
@ -39,7 +39,7 @@ from calibre.gui2.widgets2 import Dialog
|
||||
from calibre.utils.config import JSONConfig
|
||||
from calibre.utils.icu import numeric_sort_key as sort_key
|
||||
from calibre.utils.resources import get_image_path as I
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
ENTRY_ROLE = Qt.ItemDataRole.UserRole
|
||||
|
||||
@ -237,7 +237,7 @@ else:
|
||||
|
||||
def entry_to_item(entry, parent):
|
||||
icon_path = entry.get('Icon') or I('blank.png')
|
||||
if not isinstance(icon_path, string_or_bytes):
|
||||
if not isinstance(icon_path, (str, bytes)):
|
||||
icon_path = I('blank.png')
|
||||
ans = QListWidgetItem(QIcon(icon_path), entry.get('Name') or _('Unknown'), parent)
|
||||
ans.setData(ENTRY_ROLE, entry)
|
||||
|
||||
@ -31,7 +31,6 @@ from calibre.customize.ui import preferences_plugins
|
||||
from calibre.gui2.complete2 import EditWithComplete
|
||||
from calibre.gui2.widgets import HistoryLineEdit
|
||||
from calibre.utils.config import ConfigProxy
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class AbortCommit(Exception):
|
||||
@ -190,7 +189,7 @@ class Setting:
|
||||
else:
|
||||
self.gui_obj.clear()
|
||||
for x in choices:
|
||||
if isinstance(x, string_or_bytes):
|
||||
if isinstance(x, (str, bytes)):
|
||||
x = (x, x)
|
||||
self.gui_obj.addItem(x[0], (x[1]))
|
||||
self.set_gui_val(self.get_config_val(default=False))
|
||||
|
||||
@ -7,7 +7,6 @@ import os
|
||||
from qt.core import QDialog, QFileDialog, QObject
|
||||
|
||||
from calibre.gui2.linux_file_dialogs import dialog_name, image_extensions
|
||||
from polyglot.builtins import string_or_bytes
|
||||
from polyglot.urllib import unquote
|
||||
|
||||
|
||||
@ -89,7 +88,7 @@ class FileDialog(QObject):
|
||||
else:
|
||||
initial_dir = dynamic.get(self.dialog_name,
|
||||
os.path.expanduser(default_dir))
|
||||
if not isinstance(initial_dir, string_or_bytes):
|
||||
if not isinstance(initial_dir, (str, bytes)):
|
||||
initial_dir = os.path.expanduser(default_dir)
|
||||
if not initial_dir or (not os.path.exists(initial_dir) and not (
|
||||
mode == QFileDialog.FileMode.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
|
||||
|
||||
@ -17,7 +17,7 @@ from calibre.gui2.dialogs.search import SearchDialog
|
||||
from calibre.gui2.widgets import stylesheet_for_lineedit
|
||||
from calibre.utils.icu import primary_sort_key
|
||||
from calibre.utils.localization import pgettext
|
||||
from polyglot.builtins import native_string_type, string_or_bytes
|
||||
from polyglot.builtins import native_string_type
|
||||
|
||||
|
||||
class AsYouType(str):
|
||||
@ -215,7 +215,7 @@ class SearchBox2(QComboBox): # {{{
|
||||
self.parse_error_action.setToolTip(tooltip)
|
||||
|
||||
def search_done(self, ok):
|
||||
if isinstance(ok, string_or_bytes):
|
||||
if isinstance(ok, (str, bytes)):
|
||||
self.setToolTip(ok)
|
||||
self.show_parse_error_action(True, tooltip=ok)
|
||||
ok = False
|
||||
|
||||
@ -20,7 +20,6 @@ from calibre.ptempfile import PersistentTemporaryDirectory, reset_base_dir
|
||||
from calibre.startup import connect_lambda
|
||||
from calibre.utils.webengine import setup_profile
|
||||
from polyglot.binary import as_base64_bytes, from_base64_bytes
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class DownloadItem(QWidget):
|
||||
@ -213,7 +212,7 @@ class Main(MainWindow):
|
||||
os.remove(path)
|
||||
return
|
||||
tags = self.data['tags']
|
||||
if isinstance(tags, string_or_bytes):
|
||||
if isinstance(tags, (str, bytes)):
|
||||
tags = list(filter(None, [x.strip() for x in tags.split(',')]))
|
||||
data = json.dumps({'path': path, 'tags': tags})
|
||||
if not isinstance(data, bytes):
|
||||
|
||||
@ -88,7 +88,7 @@ from calibre.utils.imghdr import identify
|
||||
from calibre.utils.ipc.launch import exe_path, macos_edit_book_bundle_path
|
||||
from calibre.utils.localization import ngettext
|
||||
from calibre.utils.tdir_in_cache import tdir_in_cache
|
||||
from polyglot.builtins import as_bytes, iteritems, itervalues, string_or_bytes
|
||||
from polyglot.builtins import as_bytes, iteritems, itervalues
|
||||
from polyglot.urllib import urlparse
|
||||
|
||||
_diff_dialogs = []
|
||||
@ -1565,7 +1565,7 @@ class Boss(QObject):
|
||||
|
||||
@in_thread_job
|
||||
def export_requested(self, name_or_names, path):
|
||||
if isinstance(name_or_names, string_or_bytes):
|
||||
if isinstance(name_or_names, (str, bytes)):
|
||||
return self.export_file(name_or_names, path)
|
||||
for name in name_or_names:
|
||||
dest = os.path.abspath(os.path.join(path, name))
|
||||
|
||||
@ -36,11 +36,10 @@ from calibre.gui2.tweak_book.editor import CLASS_ATTRIBUTE_PROPERTY, CSS_PROPERT
|
||||
from calibre.gui2.tweak_book.editor.help import help_url
|
||||
from calibre.gui2.tweak_book.editor.text import TextEdit
|
||||
from calibre.utils.icu import primary_sort_key, utf16_length
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def create_icon(text, palette=None, sz=None, divider=2, fill='white'):
|
||||
if isinstance(fill, string_or_bytes):
|
||||
if isinstance(fill, (str, bytes)):
|
||||
fill = QColor(fill)
|
||||
sz = sz or math.ceil(tprefs['toolbar_icon_size'] * QApplication.instance().devicePixelRatio())
|
||||
if palette is None:
|
||||
|
||||
@ -68,7 +68,6 @@ from calibre.utils.config import dynamic, prefs
|
||||
from calibre.utils.ipc.pool import Pool
|
||||
from calibre.utils.resources import get_image_path as I
|
||||
from calibre.utils.resources import get_path as P
|
||||
from polyglot.builtins import string_or_bytes
|
||||
from polyglot.queue import Empty, Queue
|
||||
|
||||
|
||||
@ -656,7 +655,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{
|
||||
|
||||
def handle_cli_args(self, args):
|
||||
from urllib.parse import parse_qs, unquote, urlparse
|
||||
if isinstance(args, string_or_bytes):
|
||||
if isinstance(args, (str, bytes)):
|
||||
args = [args]
|
||||
files, urls = [], []
|
||||
for p in args:
|
||||
|
||||
@ -11,7 +11,6 @@ from threading import Thread
|
||||
from uuid import uuid4
|
||||
|
||||
from calibre.utils.localization import _
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
base = sys.extensions_location if hasattr(sys, 'new_app_layout') else os.path.dirname(sys.executable)
|
||||
HELPER = os.path.join(base, 'calibre-file-dialog.exe')
|
||||
@ -74,7 +73,7 @@ def serialize_file_types(file_types):
|
||||
buf.append(struct.pack(f'=H{len(x)}s', len(x), x))
|
||||
for name, extensions in file_types:
|
||||
add(name or _('Files'))
|
||||
if isinstance(extensions, string_or_bytes):
|
||||
if isinstance(extensions, (str, bytes)):
|
||||
extensions = extensions.split()
|
||||
add('; '.join('*.' + ext.lower() for ext in extensions))
|
||||
return b''.join(buf)
|
||||
|
||||
@ -17,7 +17,6 @@ from calibre.customize.conversion import DummyReporter
|
||||
from calibre.ebooks.metadata import format_isbn
|
||||
from calibre.library.catalogs import FIELDS, TEMPLATE_ALLOWED_FIELDS
|
||||
from calibre.utils.localization import _
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class BIBTEX(CatalogPlugin):
|
||||
@ -220,10 +219,10 @@ class BIBTEX(CatalogPlugin):
|
||||
bibtex_entry.append(f'year = "{item.year}"')
|
||||
bibtex_entry.append('month = "{}"'.format(bibtexdict.utf8ToBibtex(strftime('%b', item))))
|
||||
|
||||
elif field.startswith('#') and isinstance(item, string_or_bytes):
|
||||
elif field.startswith('#') and isinstance(item, (str, bytes)):
|
||||
bibtex_entry.append(f'custom_{field[1:]} = "{bibtexdict.utf8ToBibtex(item)}"')
|
||||
|
||||
elif isinstance(item, string_or_bytes):
|
||||
elif isinstance(item, (str, bytes)):
|
||||
# elif field in ['title', 'publisher', 'cover', 'uuid', 'ondevice',
|
||||
# 'author_sort', 'series', 'title_sort'] :
|
||||
bibtex_entry.append(f'{field} = "{bibtexdict.utf8ToBibtex(item)}"')
|
||||
@ -357,7 +356,7 @@ class BIBTEX(CatalogPlugin):
|
||||
bibtexc.ascii_bibtex = True
|
||||
|
||||
# Check citation choice and go to default in case of bad CLI
|
||||
if isinstance(opts.impcit, string_or_bytes):
|
||||
if isinstance(opts.impcit, (str, bytes)):
|
||||
if opts.impcit == 'False':
|
||||
citation_bibtex= False
|
||||
elif opts.impcit == 'True':
|
||||
@ -369,7 +368,7 @@ class BIBTEX(CatalogPlugin):
|
||||
citation_bibtex= opts.impcit
|
||||
|
||||
# Check add file entry and go to default in case of bad CLI
|
||||
if isinstance(opts.addfiles, string_or_bytes):
|
||||
if isinstance(opts.addfiles, (str, bytes)):
|
||||
if opts.addfiles == 'False':
|
||||
addfiles_bibtex = False
|
||||
elif opts.addfiles == 'True':
|
||||
|
||||
@ -16,7 +16,6 @@ from calibre.library.field_metadata import FieldMetadata
|
||||
from calibre.utils.config import tweaks
|
||||
from calibre.utils.date import parse_date
|
||||
from calibre.utils.localization import _
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class CustomColumns:
|
||||
@ -218,7 +217,7 @@ class CustomColumns:
|
||||
ans = ans.split(data['multiple_seps']['cache_to_list']) if ans else []
|
||||
if data['display'].get('sort_alpha', False):
|
||||
ans.sort(key=lambda x:x.lower())
|
||||
if data['datatype'] == 'datetime' and isinstance(ans, string_or_bytes):
|
||||
if data['datatype'] == 'datetime' and isinstance(ans, (str, bytes)):
|
||||
from calibre.db.tables import UNDEFINED_DATE, c_parse
|
||||
ans = c_parse(ans)
|
||||
if ans is UNDEFINED_DATE:
|
||||
@ -250,7 +249,7 @@ class CustomColumns:
|
||||
ans = ans.split(data['multiple_seps']['cache_to_list']) if ans else []
|
||||
if data['display'].get('sort_alpha', False):
|
||||
ans.sort(key=lambda x: x.lower())
|
||||
if data['datatype'] == 'datetime' and isinstance(ans, string_or_bytes):
|
||||
if data['datatype'] == 'datetime' and isinstance(ans, (str, bytes)):
|
||||
from calibre.db.tables import UNDEFINED_DATE, c_parse
|
||||
ans = c_parse(ans)
|
||||
if ans is UNDEFINED_DATE:
|
||||
|
||||
@ -55,7 +55,7 @@ from calibre.utils.localization import _, calibre_langcode_to_name, canonicalize
|
||||
from calibre.utils.recycle_bin import delete_file, delete_tree
|
||||
from calibre.utils.resources import get_path as P
|
||||
from calibre.utils.search_query_parser import saved_searches, set_saved_searches
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
copyfile = os.link if hasattr(os, 'link') else shutil.copyfile
|
||||
SPOOL_SIZE = 30*1024*1024
|
||||
@ -1121,7 +1121,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
||||
|
||||
def find_identical_books(self, mi):
|
||||
fuzzy_title_patterns = [(re.compile(pat, re.IGNORECASE) if
|
||||
isinstance(pat, string_or_bytes) else pat, repl) for pat, repl in
|
||||
isinstance(pat, (str, bytes)) else pat, repl) for pat, repl in
|
||||
[
|
||||
(r'[\[\](){}<>\'";,:#]', ''),
|
||||
(get_title_sort_pat(), ''),
|
||||
@ -1404,7 +1404,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
||||
id_ = index if index_is_id else self.id(index)
|
||||
raise NoSuchFormat(f'Record {id_} has no {fmt} file')
|
||||
if windows_atomic_move is not None:
|
||||
if not isinstance(dest, string_or_bytes):
|
||||
if not isinstance(dest, (str, bytes)):
|
||||
raise Exception('Error, you must pass the dest as a path when'
|
||||
' using windows_atomic_move')
|
||||
if dest:
|
||||
@ -1459,7 +1459,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
||||
id = index if index_is_id else self.id(index)
|
||||
path = os.path.join(self.library_path, self.path(id, index_is_id=True), 'cover.jpg')
|
||||
if windows_atomic_move is not None:
|
||||
if not isinstance(dest, string_or_bytes):
|
||||
if not isinstance(dest, (str, bytes)):
|
||||
raise Exception('Error, you must pass the dest as a path when'
|
||||
' using windows_atomic_move')
|
||||
if os.access(path, os.R_OK) and dest and not samefile(dest, path):
|
||||
@ -2340,7 +2340,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
||||
# force_changes has no effect on cover manipulation
|
||||
if mi.cover_data[1] is not None:
|
||||
doit(self.set_cover, id, mi.cover_data[1], commit=False)
|
||||
elif isinstance(mi.cover, string_or_bytes) and mi.cover:
|
||||
elif isinstance(mi.cover, (str, bytes)) and mi.cover:
|
||||
if os.access(mi.cover, os.R_OK):
|
||||
with open(mi.cover, 'rb') as f:
|
||||
raw = f.read()
|
||||
@ -2647,7 +2647,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
||||
def set_pubdate(self, id, dt, notify=True, commit=True):
|
||||
if not dt:
|
||||
dt = UNDEFINED_DATE
|
||||
if isinstance(dt, string_or_bytes):
|
||||
if isinstance(dt, (str, bytes)):
|
||||
dt = parse_only_date(dt)
|
||||
self.conn.execute('UPDATE books SET pubdate=? WHERE id=?', (dt, id))
|
||||
self.data.set(id, self.FIELD_MAP['pubdate'], dt, row_is_id=True)
|
||||
|
||||
@ -21,7 +21,7 @@ from calibre.utils.config import prefs, tweaks
|
||||
from calibre.utils.date import isoformat, timestampfromdt
|
||||
from calibre.utils.icu import numeric_sort_key as sort_key
|
||||
from calibre.utils.localization import _
|
||||
from polyglot.builtins import iteritems, string_or_bytes
|
||||
from polyglot.builtins import iteritems
|
||||
|
||||
|
||||
def ensure_val(x, *allowed):
|
||||
@ -107,7 +107,7 @@ def book_to_json(ctx, rd, db, book_id,
|
||||
if (fm and fm['is_category'] and not fm['is_csp'] and
|
||||
key != 'formats' and fm['datatype'] != 'rating'):
|
||||
categories = mi.get(key) or []
|
||||
if isinstance(categories, string_or_bytes):
|
||||
if isinstance(categories, (str, bytes)):
|
||||
categories = [categories]
|
||||
category_urls[key] = dbtags = {}
|
||||
for category in categories:
|
||||
|
||||
@ -25,7 +25,7 @@ from calibre.srv.utils import HTTP1, HTTP11, Cookie, MultiDict, get_translator_f
|
||||
from calibre.utils.monotonic import monotonic
|
||||
from calibre.utils.speedups import ReadOnlyFileBuffer
|
||||
from polyglot import http_client, reprlib
|
||||
from polyglot.builtins import error_message, iteritems, reraise, string_or_bytes
|
||||
from polyglot.builtins import error_message, iteritems, reraise
|
||||
|
||||
Range = namedtuple('Range', 'start stop size')
|
||||
MULTIPART_SEPARATOR = uuid.uuid4().hex
|
||||
@ -315,7 +315,7 @@ def filesystem_file_output(output, outheaders, stat_result):
|
||||
etag = getattr(output, 'etag', None)
|
||||
if etag is None:
|
||||
oname = output.name or ''
|
||||
if not isinstance(oname, string_or_bytes):
|
||||
if not isinstance(oname, (str, bytes)):
|
||||
oname = str(oname)
|
||||
etag = hashlib.sha1((str(stat_result.st_mtime) + force_unicode(oname)).encode('utf-8')).hexdigest()
|
||||
else:
|
||||
@ -652,7 +652,7 @@ class HTTPConnection(HTTPRequest):
|
||||
output = filesystem_file_output(output, outheaders, stat_result)
|
||||
if 'Content-Type' not in outheaders:
|
||||
output_name = output.name
|
||||
if not isinstance(output_name, string_or_bytes):
|
||||
if not isinstance(output_name, (str, bytes)):
|
||||
output_name = str(output_name)
|
||||
mt = guess_type(output_name)[0]
|
||||
if mt:
|
||||
@ -661,7 +661,7 @@ class HTTPConnection(HTTPRequest):
|
||||
outheaders['Content-Type'] = mt
|
||||
else:
|
||||
outheaders['Content-Type'] = 'application/octet-stream'
|
||||
elif isinstance(output, string_or_bytes):
|
||||
elif isinstance(output, (str, bytes)):
|
||||
output = dynamic_output(output, outheaders)
|
||||
elif hasattr(output, 'read'):
|
||||
output = ReadableOutput(output)
|
||||
|
||||
@ -18,14 +18,14 @@ from calibre.srv.utils import get_library_data, http_date
|
||||
from calibre.utils.cleantext import clean_xml_chars
|
||||
from calibre.utils.date import dt_as_local, is_date_undefined, timestampfromdt
|
||||
from calibre.utils.localization import _
|
||||
from polyglot.builtins import as_bytes, string_or_bytes
|
||||
from polyglot.builtins import as_bytes
|
||||
from polyglot.urllib import urlencode
|
||||
|
||||
# /mobile {{{
|
||||
|
||||
|
||||
def clean(x):
|
||||
if isinstance(x, string_or_bytes):
|
||||
if isinstance(x, (str, bytes)):
|
||||
x = clean_xml_chars(x)
|
||||
return x
|
||||
|
||||
|
||||
@ -22,7 +22,6 @@ from calibre.utils.filenames import atomic_rename
|
||||
from calibre.utils.imghdr import what
|
||||
from calibre.utils.resources import get_image_path as I
|
||||
from calibre_extensions import imageops
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
# Utilities {{{
|
||||
@ -515,7 +514,7 @@ def quantize_image(img, max_colors=256, dither=True, palette=''):
|
||||
img = image_from_data(img)
|
||||
if img.hasAlphaChannel():
|
||||
img = blend_image(img)
|
||||
if palette and isinstance(palette, string_or_bytes):
|
||||
if palette and isinstance(palette, (str, bytes)):
|
||||
palette = palette.split()
|
||||
return imageops.quantize(img, int(max_colors), dither, tuple(QColor(x).rgb() for x in palette))
|
||||
|
||||
|
||||
@ -6,7 +6,6 @@ import os
|
||||
from struct import error, unpack
|
||||
|
||||
from calibre.utils.speedups import ReadOnlyFileBuffer
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
''' Recognize image file formats and sizes based on their first few bytes.'''
|
||||
|
||||
@ -16,7 +15,7 @@ HSIZE = 120
|
||||
def what(file, h=None):
|
||||
' Recognize image headers '
|
||||
if h is None:
|
||||
if isinstance(file, string_or_bytes):
|
||||
if isinstance(file, (str, bytes)):
|
||||
with open(file, 'rb') as f:
|
||||
h = f.read(HSIZE)
|
||||
else:
|
||||
|
||||
@ -14,7 +14,7 @@ from calibre.ptempfile import PersistentTemporaryFile, base_dir
|
||||
from calibre.utils.config import prefs
|
||||
from calibre.utils.serialize import msgpack_dumps
|
||||
from polyglot.binary import as_hex_unicode
|
||||
from polyglot.builtins import environ_item, native_string_type, string_or_bytes
|
||||
from polyglot.builtins import environ_item, native_string_type
|
||||
|
||||
if iswindows:
|
||||
try:
|
||||
@ -184,7 +184,7 @@ class Worker:
|
||||
_cwd = cwd
|
||||
if priority is None:
|
||||
priority = prefs['worker_process_priority']
|
||||
cmd = [exe] if isinstance(exe, string_or_bytes) else exe
|
||||
cmd = [exe] if isinstance(exe, (str, bytes)) else exe
|
||||
args = {
|
||||
'env': env,
|
||||
'cwd': _cwd,
|
||||
|
||||
@ -25,7 +25,7 @@ from calibre.utils.ipc.launch import Worker
|
||||
from calibre.utils.ipc.worker import PARALLEL_FUNCS
|
||||
from calibre.utils.serialize import pickle_loads
|
||||
from polyglot.binary import as_hex_unicode
|
||||
from polyglot.builtins import environ_item, string_or_bytes
|
||||
from polyglot.builtins import environ_item
|
||||
from polyglot.queue import Empty, Queue
|
||||
|
||||
server_counter = count()
|
||||
@ -125,7 +125,7 @@ class Server(Thread):
|
||||
redirect_output = not gui
|
||||
|
||||
cw = self.do_launch(gui, redirect_output, rfile, job_name=job_name)
|
||||
if isinstance(cw, string_or_bytes):
|
||||
if isinstance(cw, (str, bytes)):
|
||||
raise CriticalError('Failed to launch worker process:\n'+force_unicode(cw))
|
||||
if DEBUG:
|
||||
print(f'Worker Launch took: {time.monotonic() - start:.2f} seconds')
|
||||
|
||||
@ -16,7 +16,7 @@ from calibre.constants import iswindows
|
||||
from calibre.utils.ipc import eintr_retry_call
|
||||
from calibre.utils.ipc.launch import Worker, windows_creationflags_for_worker_process
|
||||
from calibre.utils.monotonic import monotonic
|
||||
from polyglot.builtins import environ_item, string_or_bytes
|
||||
from polyglot.builtins import environ_item
|
||||
|
||||
if iswindows:
|
||||
from multiprocessing.connection import PipeConnection as Connection
|
||||
@ -153,7 +153,7 @@ def start_pipe_worker(command, env=None, priority='normal', **process_args):
|
||||
args['env']['CALIBRE_WORKER_NICENESS'] = str(niceness)
|
||||
|
||||
exe = w.executable
|
||||
cmd = [exe] if isinstance(exe, string_or_bytes) else exe
|
||||
cmd = [exe] if isinstance(exe, (str, bytes)) else exe
|
||||
p = subprocess.Popen(cmd + ['--pipe-worker', command], **args)
|
||||
finally:
|
||||
if iswindows and pass_fds:
|
||||
|
||||
@ -13,7 +13,6 @@ from plistlib import loads
|
||||
|
||||
from calibre.ptempfile import TemporaryDirectory
|
||||
from calibre.utils.icu import numeric_sort_key
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
application_locations = ('/Applications', '~/Applications', '~/Desktop')
|
||||
|
||||
@ -241,7 +240,7 @@ def get_extensions_from_utis(utis, plist):
|
||||
for decl in plist.get(key, ()):
|
||||
if isinstance(decl, dict):
|
||||
uti = decl.get('UTTypeIdentifier')
|
||||
if isinstance(uti, string_or_bytes):
|
||||
if isinstance(uti, (str, bytes)):
|
||||
spec = decl.get('UTTypeTagSpecification')
|
||||
if isinstance(spec, dict):
|
||||
ext = spec.get('public.filename-extension')
|
||||
@ -291,10 +290,10 @@ def get_bundle_data(path):
|
||||
extensions |= get_extensions_from_utis(utis, plist)
|
||||
else:
|
||||
for ext in dtype.get('CFBundleTypeExtensions', ()):
|
||||
if isinstance(ext, string_or_bytes):
|
||||
if isinstance(ext, (str, bytes)):
|
||||
extensions.add(ext.lower())
|
||||
for mt in dtype.get('CFBundleTypeMIMETypes', ()):
|
||||
if isinstance(mt, string_or_bytes):
|
||||
if isinstance(mt, (str, bytes)):
|
||||
for ext in mimetypes.guess_all_extensions(mt, strict=False):
|
||||
extensions.add(ext.lower())
|
||||
return ans
|
||||
|
||||
@ -53,8 +53,6 @@ from email.base64mime import body_encode as encode_base64
|
||||
from functools import partial
|
||||
from sys import stderr
|
||||
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
__all__ = [
|
||||
'SMTP',
|
||||
'SMTPAuthenticationError',
|
||||
@ -735,7 +733,7 @@ class SMTP:
|
||||
self.rset()
|
||||
raise SMTPSenderRefused(code, resp, from_addr)
|
||||
senderrs = {}
|
||||
if isinstance(to_addrs, string_or_bytes):
|
||||
if isinstance(to_addrs, (str, bytes)):
|
||||
to_addrs = [to_addrs]
|
||||
for each in to_addrs:
|
||||
code, resp = self.rcpt(each, rcpt_options)
|
||||
|
||||
@ -13,7 +13,6 @@ from io import BytesIO
|
||||
from calibre.constants import filesystem_encoding, iswindows
|
||||
from calibre.ptempfile import PersistentTemporaryFile, TemporaryDirectory
|
||||
from calibre.utils.filenames import make_long_path_useable
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def as_unicode(x):
|
||||
@ -29,7 +28,7 @@ class StreamAsPath:
|
||||
|
||||
def __enter__(self):
|
||||
self.temppath = None
|
||||
if isinstance(self.stream, string_or_bytes):
|
||||
if isinstance(self.stream, (str, bytes)):
|
||||
return as_unicode(self.stream)
|
||||
name = getattr(self.stream, 'name', None)
|
||||
if name and os.access(name, os.R_OK):
|
||||
|
||||
@ -20,7 +20,7 @@ from calibre import sanitize_file_name
|
||||
from calibre.constants import filesystem_encoding
|
||||
from calibre.ebooks.chardet import detect
|
||||
from calibre.ptempfile import SpooledTemporaryFile
|
||||
from polyglot.builtins import as_bytes, string_or_bytes
|
||||
from polyglot.builtins import as_bytes
|
||||
|
||||
try:
|
||||
from calibre_extensions.speedup import pread_all
|
||||
@ -782,7 +782,7 @@ class ZipFile:
|
||||
self.comment = b''
|
||||
|
||||
# Check if we were passed a file-like object
|
||||
if isinstance(file, string_or_bytes):
|
||||
if isinstance(file, (str, bytes)):
|
||||
self._filePassed = 0
|
||||
self.filename = file
|
||||
modeDict = {'r': 'rb', 'w': 'wb', 'a': 'r+b'}
|
||||
|
||||
@ -16,7 +16,6 @@ from calibre import force_unicode, replace_entities, strftime
|
||||
from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars
|
||||
from calibre.utils.date import dt_factory, local_tz, utcnow
|
||||
from calibre.utils.logging import default_log
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
class Article:
|
||||
@ -25,7 +24,7 @@ class Article:
|
||||
from lxml import html
|
||||
self.downloaded = False
|
||||
self.id = id
|
||||
if not title or not isinstance(title, string_or_bytes):
|
||||
if not title or not isinstance(title, (str, bytes)):
|
||||
title = _('Unknown')
|
||||
title = force_unicode(title, 'utf-8')
|
||||
self._title = clean_xml_chars(title).strip()
|
||||
|
||||
@ -33,7 +33,6 @@ from calibre.web.feeds import Feed, feed_from_xml, feeds_from_index, templates
|
||||
from calibre.web.fetch.simple import AbortArticle, RecursiveFetcher
|
||||
from calibre.web.fetch.simple import option_parser as web2disk_option_parser
|
||||
from calibre.web.fetch.utils import prepare_masthead_image
|
||||
from polyglot.builtins import string_or_bytes
|
||||
|
||||
|
||||
def classes(classes):
|
||||
@ -1751,7 +1750,7 @@ class BasicNewsRecipe(Recipe):
|
||||
parsed_feeds = []
|
||||
br = self.browser
|
||||
for obj in feeds:
|
||||
if isinstance(obj, string_or_bytes):
|
||||
if isinstance(obj, (str, bytes)):
|
||||
title, url = None, obj
|
||||
else:
|
||||
title, url = obj
|
||||
@ -1812,7 +1811,7 @@ class BasicNewsRecipe(Recipe):
|
||||
'''
|
||||
if tag is None:
|
||||
return ''
|
||||
if isinstance(tag, string_or_bytes):
|
||||
if isinstance(tag, (str, bytes)):
|
||||
return tag
|
||||
if callable(getattr(tag, 'xpath', None)) and not hasattr(tag, 'contents'): # a lxml tag
|
||||
from lxml.etree import tostring
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
|
||||
import re
|
||||
|
||||
from polyglot.builtins import string_or_bytes, unicode_type
|
||||
from polyglot.builtins import unicode_type
|
||||
|
||||
from .namespaces import (
|
||||
ANIMNS,
|
||||
@ -212,7 +212,7 @@ def cnv_NCName(attribute, arg, element):
|
||||
''' NCName is defined in http://www.w3.org/TR/REC-xml-names/#NT-NCName
|
||||
Essentially an XML name minus ':'
|
||||
'''
|
||||
if isinstance(arg, string_or_bytes):
|
||||
if isinstance(arg, (str, bytes)):
|
||||
return make_NCName(arg)
|
||||
else:
|
||||
return arg.getAttrNS(STYLENS, 'name')
|
||||
@ -269,7 +269,7 @@ pattern_points = re.compile(r'-?[0-9]+,-?[0-9]+([ ]+-?[0-9]+,-?[0-9]+)*')
|
||||
|
||||
def cnv_points(attribute, arg, element):
|
||||
global pattern_points
|
||||
if isinstance(arg, string_or_bytes):
|
||||
if isinstance(arg, (str, bytes)):
|
||||
if not pattern_points.match(arg):
|
||||
raise ValueError('x,y are separated by a comma and the points are separated by white spaces')
|
||||
return arg
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user