diff --git a/src/calibre/__init__.py b/src/calibre/__init__.py index 98b41ff80f..c1fc63d208 100644 --- a/src/calibre/__init__.py +++ b/src/calibre/__init__.py @@ -5,7 +5,7 @@ __docformat__ = 'restructuredtext en' import sys, os, re, time, random, warnings -from polyglot.builtins import codepoint_to_chr, unicode_type, hasenv, native_string_type +from polyglot.builtins import codepoint_to_chr, hasenv, native_string_type from math import floor from functools import partial @@ -71,7 +71,7 @@ def get_types_map(): def to_unicode(raw, encoding='utf-8', errors='strict'): - if isinstance(raw, unicode_type): + if isinstance(raw, str): return raw return raw.decode(encoding, errors) @@ -259,7 +259,7 @@ def get_parsed_proxy(typ='http', debug=True): traceback.print_exc() else: if debug: - prints('Using http proxy', unicode_type(ans)) + prints('Using http proxy', str(ans)) return ans @@ -419,7 +419,7 @@ def strftime(fmt, t=None): fmt = fmt.decode('mbcs' if iswindows else 'utf-8', 'replace') ans = time.strftime(fmt, t) if early_year: - ans = ans.replace('_early year hack##', unicode_type(orig_year)) + ans = ans.replace('_early year hack##', str(orig_year)) return ans @@ -531,7 +531,7 @@ def force_unicode(obj, enc=preferred_encoding): def as_unicode(obj, enc=preferred_encoding): if not isbytestring(obj): try: - obj = unicode_type(obj) + obj = str(obj) except Exception: try: obj = native_string_type(obj) @@ -554,7 +554,7 @@ def human_readable(size, sep=' '): if size < (1 << ((i + 1) * 10)): divisor, suffix = (1 << (i * 10)), candidate break - size = unicode_type(float(size)/divisor) + size = str(float(size)/divisor) if size.find(".") > -1: size = size[:size.find(".")+2] if size.endswith('.0'): diff --git a/src/calibre/constants.py b/src/calibre/constants.py index 205f2ac343..d305f7d69f 100644 --- a/src/calibre/constants.py +++ b/src/calibre/constants.py @@ -1,12 +1,12 @@ #!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2015, Kovid Goyal -from polyglot.builtins import unicode_type, environ_item, hasenv +from polyglot.builtins import environ_item, hasenv import sys, locale, codecs, os, collections, collections.abc __appname__ = 'calibre' numeric_version = (5, 29, 0) -__version__ = '.'.join(map(unicode_type, numeric_version)) +__version__ = '.'.join(map(str, numeric_version)) git_version = None __author__ = "Kovid Goyal " diff --git a/src/calibre/customize/__init__.py b/src/calibre/customize/__init__.py index 048fbe7c41..964e61dbdb 100644 --- a/src/calibre/customize/__init__.py +++ b/src/calibre/customize/__init__.py @@ -6,7 +6,6 @@ from calibre.constants import numeric_version, iswindows, ismacos from calibre.ptempfile import PersistentTemporaryFile -from polyglot.builtins import unicode_type if iswindows: platform = 'windows' @@ -207,7 +206,7 @@ def size_dialog(): config_dialog.exec_() if config_dialog.result() == QDialog.DialogCode.Accepted: - sc = unicode_type(sc.text()).strip() + sc = str(sc.text()).strip() customize_plugin(self, sc) geom = bytearray(config_dialog.saveGeometry()) diff --git a/src/calibre/customize/conversion.py b/src/calibre/customize/conversion.py index 60aebf0e5a..5cda8c420e 100644 --- a/src/calibre/customize/conversion.py +++ b/src/calibre/customize/conversion.py @@ -7,7 +7,6 @@ from calibre import CurrentDir from calibre.customize import Plugin -from polyglot.builtins import unicode_type class ConversionOption: @@ -81,7 +80,7 @@ def validate_parameters(self): self.option.choices: raise ValueError('OpRec: %s: Recommended value not in choices'% self.option.name) - if not (isinstance(self.recommended_value, (numbers.Number, bytes, unicode_type)) or self.recommended_value is None): + if not (isinstance(self.recommended_value, (numbers.Number, bytes, str)) or self.recommended_value is None): raise ValueError('OpRec: %s:'%self.option.name + repr( self.recommended_value) + ' is not a string or a number') @@ -342,7 +341,7 @@ def convert(self, oeb_book, output, input_plugin, opts, log): @property def is_periodical(self): return self.oeb.metadata.publication_type and \ - unicode_type(self.oeb.metadata.publication_type[0]).startswith('periodical:') + str(self.oeb.metadata.publication_type[0]).startswith('periodical:') def specialize_options(self, log, opts, input_fmt): ''' diff --git a/src/calibre/customize/ui.py b/src/calibre/customize/ui.py index f5eda15643..25b8348293 100644 --- a/src/calibre/customize/ui.py +++ b/src/calibre/customize/ui.py @@ -22,7 +22,7 @@ plugin_dir, OptionParser) from calibre.ebooks.metadata.sources.base import Source from calibre.constants import DEBUG, numeric_version, system_plugins_loc -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues builtin_names = frozenset(p.name for p in builtin_plugins) BLACKLISTED_PLUGINS = frozenset({'Marvin XD', 'iOS reader applications'}) @@ -781,7 +781,7 @@ def build_plugin(path): from calibre import prints from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.zipfile import ZipFile, ZIP_STORED - path = unicode_type(path) + path = str(path) names = frozenset(os.listdir(path)) if '__init__.py' not in names: prints(path, ' is not a valid plugin') diff --git a/src/calibre/customize/zipplugin.py b/src/calibre/customize/zipplugin.py index 45544b1900..b7d212da05 100644 --- a/src/calibre/customize/zipplugin.py +++ b/src/calibre/customize/zipplugin.py @@ -22,7 +22,7 @@ from calibre.customize import ( InvalidPlugin, Plugin, PluginNotFound, numeric_version, platform ) -from polyglot.builtins import itervalues, reload, string_or_bytes, unicode_type +from polyglot.builtins import itervalues, reload, string_or_bytes # PEP 302 based plugin loading mechanism, works around the bug in zipimport in # python 2.x that prevents importing from zip files in locations whose paths @@ -307,7 +307,7 @@ def load(self, path_to_zip_file): if ans.minimum_calibre_version > numeric_version: raise InvalidPlugin( 'The plugin at %s needs a version of calibre >= %s' % - (as_unicode(path_to_zip_file), '.'.join(map(unicode_type, + (as_unicode(path_to_zip_file), '.'.join(map(str, ans.minimum_calibre_version)))) if platform not in ans.supported_platforms: diff --git a/src/calibre/db/adding.py b/src/calibre/db/adding.py index ddd0878245..299780ec45 100644 --- a/src/calibre/db/adding.py +++ b/src/calibre/db/adding.py @@ -16,7 +16,7 @@ from calibre.constants import filesystem_encoding, ismacos, iswindows from calibre.ebooks import BOOK_EXTENSIONS from calibre.utils.filenames import make_long_path_useable -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues def splitext(path): @@ -71,7 +71,7 @@ def metadata_extensions(): # but not actually added) global _metadata_extensions if _metadata_extensions is None: - _metadata_extensions = frozenset(map(unicode_type, BOOK_EXTENSIONS)) | {'opf'} + _metadata_extensions = frozenset(BOOK_EXTENSIONS) | {'opf'} return _metadata_extensions @@ -146,7 +146,7 @@ def find_books_in_directory(dirpath, single_book_per_directory, compiled_rules=( for path in listdir_impl(dirpath, sort_by_mtime=True): key, ext = splitext(path) if allow_path(path, ext, compiled_rules): - books[icu_lower(key) if isinstance(key, unicode_type) else key.lower()][ext] = path + books[icu_lower(key) if isinstance(key, str) else key.lower()][ext] = path for formats in itervalues(books): if formats_ok(formats): diff --git a/src/calibre/db/backend.py b/src/calibre/db/backend.py index ead5537d70..66adc38089 100644 --- a/src/calibre/db/backend.py +++ b/src/calibre/db/backend.py @@ -50,8 +50,7 @@ from calibre.utils.icu import sort_key from calibre.utils.img import save_cover_data_to from polyglot.builtins import ( - cmp, iteritems, itervalues, native_string_type, reraise, string_or_bytes, - unicode_type + cmp, iteritems, itervalues, native_string_type, reraise, string_or_bytes ) # }}} @@ -108,7 +107,7 @@ def load_from_db(self): dict.__setitem__(self, key, val) def raw_to_object(self, raw): - if not isinstance(raw, unicode_type): + if not isinstance(raw, str): raw = raw.decode(preferred_encoding) return json.loads(raw, object_hook=from_json) @@ -352,7 +351,7 @@ def __init__(self, path): self.createscalarfunction('title_sort', title_sort, 1) self.createscalarfunction('author_to_author_sort', _author_to_author_sort, 1) - self.createscalarfunction('uuid4', lambda: unicode_type(uuid.uuid4()), + self.createscalarfunction('uuid4', lambda: str(uuid.uuid4()), 0) # Dummy functions for dynamically created filters @@ -646,10 +645,10 @@ def migrate_preference(key, default): prints('found user category case overlap', catmap[uc]) cat = catmap[uc][0] suffix = 1 - while icu_lower((cat + unicode_type(suffix))) in catmap: + while icu_lower((cat + str(suffix))) in catmap: suffix += 1 - prints('Renaming user category %s to %s'%(cat, cat+unicode_type(suffix))) - user_cats[cat + unicode_type(suffix)] = user_cats[cat] + prints('Renaming user category %s to %s'%(cat, cat+str(suffix))) + user_cats[cat + str(suffix)] = user_cats[cat] del user_cats[cat] cats_changed = True if cats_changed: @@ -755,25 +754,25 @@ def adapt_text(x, d): if d['is_multiple']: if x is None: return [] - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): x = x.split(d['multiple_seps']['ui_to_list']) x = [y.strip() for y in x if y.strip()] x = [y.decode(preferred_encoding, 'replace') if not isinstance(y, - unicode_type) else y for y in x] + str) else y for y in x] return [u' '.join(y.split()) for y in x] else: - return x if x is None or isinstance(x, unicode_type) else \ + return x if x is None or isinstance(x, str) else \ x.decode(preferred_encoding, 'replace') def adapt_datetime(x, d): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = x.decode(preferred_encoding, 'replace') x = parse_date(x, assume_utc=False, as_utc=False) return x def adapt_bool(x, d): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = x.decode(preferred_encoding, 'replace') x = x.lower() @@ -796,7 +795,7 @@ def adapt_enum(x, d): def adapt_number(x, d): if x is None: return None - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = x.decode(preferred_encoding, 'replace') if x.lower() == 'none': @@ -888,7 +887,7 @@ def initialize_tables(self): # {{{ # account for the series index column. Field_metadata knows that # the series index is one larger than the series. If you change # it here, be sure to change it there as well. - self.FIELD_MAP[unicode_type(data['num'])+'_index'] = base = base+1 + self.FIELD_MAP[str(data['num'])+'_index'] = base = base+1 self.field_metadata.set_field_record_index(label_+'_index', base, prefer_custom=True) @@ -1311,7 +1310,7 @@ def library_id(self): if getattr(self, '_library_id_', None) is None: ans = self.conn.get('SELECT uuid FROM library_id', all=False) if ans is None: - ans = unicode_type(uuid.uuid4()) + ans = str(uuid.uuid4()) self.library_id = ans else: self._library_id_ = ans @@ -1319,7 +1318,7 @@ def library_id(self): @library_id.setter def library_id(self, val): - self._library_id_ = unicode_type(val) + self._library_id_ = str(val) self.execute(''' DELETE FROM library_id; INSERT INTO library_id (uuid) VALUES (?); @@ -2026,7 +2025,7 @@ def set_conversion_options(self, options, fmt): def map_data(x): if not isinstance(x, string_or_bytes): x = native_string_type(x) - x = x.encode('utf-8') if isinstance(x, unicode_type) else x + x = x.encode('utf-8') if isinstance(x, str) else x x = pickle_binary_string(x) return x options = [(book_id, fmt.upper(), map_data(data)) for book_id, data in iteritems(options)] @@ -2067,7 +2066,7 @@ def move_library_to(self, all_paths, newloc, progress=(lambda item_name, item_co copyfile_using_links(src, dest, dest_is_dir=False) old_files.add(src) x = path_map[x] - if not isinstance(x, unicode_type): + if not isinstance(x, str): x = x.decode(filesystem_encoding, 'replace') progress(x, i+1, total) diff --git a/src/calibre/db/cache.py b/src/calibre/db/cache.py index 5a3590df80..09afc7a4a5 100644 --- a/src/calibre/db/cache.py +++ b/src/calibre/db/cache.py @@ -47,7 +47,7 @@ from calibre.utils.date import UNDEFINED_DATE, now as nowf, utcnow from calibre.utils.icu import sort_key from calibre.utils.localization import canonicalize_lang -from polyglot.builtins import cmp, iteritems, itervalues, string_or_bytes, unicode_type +from polyglot.builtins import cmp, iteritems, itervalues, string_or_bytes def api(f): @@ -579,14 +579,14 @@ def get_item_name(self, field, item_id): @read_api def get_item_id(self, field, item_name): ' Return the item id for item_name (case-insensitive) ' - rmap = {icu_lower(v) if isinstance(v, unicode_type) else v:k for k, v in iteritems(self.fields[field].table.id_map)} - return rmap.get(icu_lower(item_name) if isinstance(item_name, unicode_type) else item_name, None) + rmap = {icu_lower(v) if isinstance(v, str) else v:k for k, v in iteritems(self.fields[field].table.id_map)} + return rmap.get(icu_lower(item_name) if isinstance(item_name, str) else item_name, None) @read_api def get_item_ids(self, field, item_names): ' Return the item id for item_name (case-insensitive) ' - rmap = {icu_lower(v) if isinstance(v, unicode_type) else v:k for k, v in iteritems(self.fields[field].table.id_map)} - return {name:rmap.get(icu_lower(name) if isinstance(name, unicode_type) else name, None) for name in item_names} + rmap = {icu_lower(v) if isinstance(v, str) else v:k for k, v in iteritems(self.fields[field].table.id_map)} + return {name:rmap.get(icu_lower(name) if isinstance(name, str) else name, None) for name in item_names} @read_api def author_data(self, author_ids=None): diff --git a/src/calibre/db/categories.py b/src/calibre/db/categories.py index 6889900554..512feff4d0 100644 --- a/src/calibre/db/categories.py +++ b/src/calibre/db/categories.py @@ -8,7 +8,7 @@ import copy from functools import partial -from polyglot.builtins import iteritems, unicode_type, native_string_type +from polyglot.builtins import iteritems, native_string_type from calibre.ebooks.metadata import author_to_author_sort from calibre.utils.config_base import tweaks @@ -101,8 +101,8 @@ def clean_user_categories(dbcache): if len(comps) == 0: i = 1 while True: - if unicode_type(i) not in user_cats: - new_cats[unicode_type(i)] = user_cats[k] + if str(i) not in user_cats: + new_cats[str(i)] = user_cats[k] break i += 1 else: diff --git a/src/calibre/db/cli/cmd_add.py b/src/calibre/db/cli/cmd_add.py index b68e3c18dc..298d4453b7 100644 --- a/src/calibre/db/cli/cmd_add.py +++ b/src/calibre/db/cli/cmd_add.py @@ -21,7 +21,6 @@ from calibre.srv.changes import books_added, formats_added from calibre.utils.localization import canonicalize_lang from calibre.utils.short_uuid import uuid4 -from polyglot.builtins import unicode_type readonly = False version = 0 # change this if you change signature of implementation() @@ -296,9 +295,9 @@ def do_add( prints(' ', path) if added_ids: - prints(_('Added book ids: %s') % (', '.join(map(unicode_type, added_ids)))) + prints(_('Added book ids: %s') % (', '.join(map(str, added_ids)))) if merged_ids: - prints(_('Merged book ids: %s') % (', '.join(map(unicode_type, merged_ids)))) + prints(_('Merged book ids: %s') % (', '.join(map(str, merged_ids)))) def option_parser(get_parser, args): diff --git a/src/calibre/db/cli/cmd_list.py b/src/calibre/db/cli/cmd_list.py index 898b53f1d7..94913a8005 100644 --- a/src/calibre/db/cli/cmd_list.py +++ b/src/calibre/db/cli/cmd_list.py @@ -11,7 +11,7 @@ from calibre.db.cli.utils import str_width from calibre.ebooks.metadata import authors_to_string from calibre.utils.date import isoformat -from polyglot.builtins import as_bytes, iteritems, unicode_type +from polyglot.builtins import as_bytes, iteritems readonly = True version = 0 # change this if you change signature of implementation() @@ -123,10 +123,10 @@ def prepare_output_table(fields, book_ids, data, metadata): ans.append(row) for field in fields: if field == 'id': - row.append(unicode_type(book_id)) + row.append(str(book_id)) continue val = data.get(field.replace('*', '#'), {}).get(book_id) - row.append(unicode_type(val).replace('\n', ' ')) + row.append(str(val).replace('\n', ' ')) return ans @@ -308,7 +308,7 @@ def option_parser(get_parser, args): def main(opts, args, dbctx): afields = set(FIELDS) | {'id'} if opts.fields.strip(): - fields = [unicode_type(f.strip().lower()) for f in opts.fields.split(',')] + fields = [str(f.strip().lower()) for f in opts.fields.split(',')] else: fields = [] diff --git a/src/calibre/db/cli/cmd_list_categories.py b/src/calibre/db/cli/cmd_list_categories.py index 6344072316..cb73569ae3 100644 --- a/src/calibre/db/cli/cmd_list_categories.py +++ b/src/calibre/db/cli/cmd_list_categories.py @@ -8,7 +8,7 @@ from textwrap import TextWrapper from calibre import prints -from polyglot.builtins import as_bytes, unicode_type +from polyglot.builtins import as_bytes readonly = True version = 0 # change this if you change signature of implementation() @@ -78,7 +78,7 @@ def do_list(fields, data, opts): widths = list(map(lambda x: 0, fields)) for i in data: for j, field in enumerate(fields): - widths[j] = max(widths[j], max(len(field), len(unicode_type(i[field])))) + widths[j] = max(widths[j], max(len(field), len(str(i[field])))) screen_width = geometry()[0] if not screen_width: @@ -109,7 +109,7 @@ def do_list(fields, data, opts): for record in data: text = [ - wrappers[i].wrap(unicode_type(record[field])) + wrappers[i].wrap(str(record[field])) for i, field in enumerate(fields) ] lines = max(map(len, text)) @@ -167,11 +167,11 @@ def fmtr(v): is_rating = category_metadata(category)['datatype'] == 'rating' for tag in category_data[category]: if is_rating: - tag.name = unicode_type(len(tag.name)) + tag.name = str(len(tag.name)) data.append({ 'category': category, 'tag_name': tag.name, - 'count': unicode_type(tag.count), + 'count': str(tag.count), 'rating': fmtr(tag.avg_rating), }) else: @@ -179,7 +179,7 @@ def fmtr(v): data.append({ 'category': category, 'tag_name': _('CATEGORY ITEMS'), - 'count': unicode_type(len(category_data[category])), + 'count': str(len(category_data[category])), 'rating': '' }) diff --git a/src/calibre/db/cli/cmd_set_metadata.py b/src/calibre/db/cli/cmd_set_metadata.py index 53eee28d77..1c36ecc529 100644 --- a/src/calibre/db/cli/cmd_set_metadata.py +++ b/src/calibre/db/cli/cmd_set_metadata.py @@ -10,7 +10,7 @@ from calibre.ebooks.metadata.book.serialize import read_cover from calibre.ebooks.metadata.opf import get_metadata from calibre.srv.changes import metadata -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems readonly = False version = 0 # change this if you change signature of implementation() @@ -181,5 +181,5 @@ def verify_int(x): if not final_mi: raise SystemExit(_('No book with id: %s in the database') % book_id) - prints(unicode_type(final_mi)) + prints(str(final_mi)) return 0 diff --git a/src/calibre/db/cli/cmd_show_metadata.py b/src/calibre/db/cli/cmd_show_metadata.py index 93ba68f240..2c0e098156 100644 --- a/src/calibre/db/cli/cmd_show_metadata.py +++ b/src/calibre/db/cli/cmd_show_metadata.py @@ -8,7 +8,6 @@ from calibre import prints from calibre.ebooks.metadata.opf2 import OPFCreator -from polyglot.builtins import unicode_type readonly = True version = 0 # change this if you change signature of implementation() @@ -53,6 +52,6 @@ def main(opts, args, dbctx): mi = OPFCreator(os.getcwd(), mi) mi.render(stdout) else: - prints(unicode_type(mi)) + prints(str(mi)) return 0 diff --git a/src/calibre/db/fields.py b/src/calibre/db/fields.py index e5818e5ecf..5f27cae4f7 100644 --- a/src/calibre/db/fields.py +++ b/src/calibre/db/fields.py @@ -18,7 +18,7 @@ from calibre.utils.icu import sort_key from calibre.utils.date import UNDEFINED_DATE, clean_date_for_sort, parse_date from calibre.utils.localization import calibre_langcode_to_name -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def bool_sort_key(bools_are_tristate): @@ -85,7 +85,7 @@ def __init__(self, name, table, bools_are_tristate, get_template_functions): self._sort_key = lambda x: sort_key(author_to_author_sort(x)) self.sort_sort_key = False self.default_value = {} if name == 'identifiers' else () if self.is_multiple else None - self.category_formatter = unicode_type + self.category_formatter = str if dt == 'rating': if self.metadata['display'].get('allow_half_stars', False): self.category_formatter = lambda x: rating_to_stars(x, True) diff --git a/src/calibre/db/lazy.py b/src/calibre/db/lazy.py index 2ca5b2f46b..5fba1ab907 100644 --- a/src/calibre/db/lazy.py +++ b/src/calibre/db/lazy.py @@ -14,7 +14,7 @@ from calibre.ebooks.metadata.book.base import Metadata, SIMPLE_GET, TOP_LEVEL_IDENTIFIERS, NULL_VALUES, ALL_METADATA_FIELDS from calibre.ebooks.metadata.book.formatter import SafeFormat from calibre.utils.date import utcnow -from polyglot.builtins import unicode_type, native_string_type +from polyglot.builtins import native_string_type # Lazy format metadata retrieval {{{ ''' @@ -46,7 +46,7 @@ def __repr__(self): @resolved def __unicode__(self): - return unicode_type(self._values) + return str(self._values) @resolved def __len__(self): diff --git a/src/calibre/db/schema_upgrades.py b/src/calibre/db/schema_upgrades.py index 1916a4d216..c957d0bde3 100644 --- a/src/calibre/db/schema_upgrades.py +++ b/src/calibre/db/schema_upgrades.py @@ -10,7 +10,7 @@ from calibre import prints from calibre.utils.date import isoformat, DEFAULT_DATE -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues class SchemaUpgrade: @@ -598,10 +598,10 @@ def upgrade_version_19(self): existing = frozenset(map(int, custom_recipes)) if id_ in existing: id_ = max(existing) + 1000 - id_ = unicode_type(id_) + id_ = str(id_) fname = custom_recipe_filename(id_, title) custom_recipes[id_] = (title, fname) - if isinstance(script, unicode_type): + if isinstance(script, str): script = script.encode('utf-8') with open(os.path.join(bdir, fname), 'wb') as f: f.write(script) diff --git a/src/calibre/db/search.py b/src/calibre/db/search.py index 6980fcb8bd..897b96d0dc 100644 --- a/src/calibre/db/search.py +++ b/src/calibre/db/search.py @@ -18,7 +18,7 @@ from calibre.utils.icu import primary_contains, sort_key from calibre.utils.localization import lang_map, canonicalize_lang from calibre.utils.search_query_parser import SearchQueryParser, ParseException -from polyglot.builtins import iteritems, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, string_or_bytes CONTAINS_MATCH = 0 EQUALS_MATCH = 1 @@ -149,7 +149,7 @@ def __call__(self, query, field_iter): if query == 'false': for v, book_ids in field_iter(): - if isinstance(v, (bytes, unicode_type)): + if isinstance(v, (bytes, str)): if isinstance(v, bytes): v = v.decode(preferred_encoding, 'replace') v = parse_date(v) @@ -159,7 +159,7 @@ def __call__(self, query, field_iter): if query == 'true': for v, book_ids in field_iter(): - if isinstance(v, (bytes, unicode_type)): + if isinstance(v, (bytes, str)): if isinstance(v, bytes): v = v.decode(preferred_encoding, 'replace') v = parse_date(v) @@ -413,7 +413,7 @@ def db(self): return self._db() def force_unicode(self, x): - if not isinstance(x, unicode_type): + if not isinstance(x, str): x = x.decode(preferred_encoding, 'replace') return x diff --git a/src/calibre/db/tests/base.py b/src/calibre/db/tests/base.py index 12a7ae691e..77ddc8b8c0 100644 --- a/src/calibre/db/tests/base.py +++ b/src/calibre/db/tests/base.py @@ -9,7 +9,6 @@ import unittest, os, shutil, tempfile, atexit, gc, time from functools import partial from io import BytesIO -from polyglot.builtins import unicode_type rmtree = partial(shutil.rmtree, ignore_errors=True) @@ -82,7 +81,7 @@ def clone_library(self, library_path): atexit.register(rmtree, self.clone_dir) self.clone_count = 0 self.clone_count += 1 - dest = os.path.join(self.clone_dir, unicode_type(self.clone_count)) + dest = os.path.join(self.clone_dir, str(self.clone_count)) shutil.copytree(library_path, dest) return dest diff --git a/src/calibre/db/tests/legacy.py b/src/calibre/db/tests/legacy.py index 743928ec79..24597c6a0f 100644 --- a/src/calibre/db/tests/legacy.py +++ b/src/calibre/db/tests/legacy.py @@ -12,7 +12,7 @@ from calibre.library.field_metadata import fm_as_dict from calibre.db.tests.base import BaseTest -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot import reprlib # Utils {{{ @@ -116,7 +116,7 @@ def get_values(db): for label, loc in iteritems(db.FIELD_MAP): if isinstance(label, numbers.Integral): label = '#'+db.custom_column_num_map[label]['label'] - label = unicode_type(label) + label = str(label) ans[label] = tuple(db.get_property(i, index_is_id=True, loc=loc) for i in db.all_ids()) if label in ('id', 'title', '#tags'): @@ -282,7 +282,7 @@ def f(x, y): # get_top_level_move_items is broken in the old db on case-insensi old = db.get_data_as_dict(prefix='test-prefix') new = ndb.get_data_as_dict(prefix='test-prefix') for o, n in zip(old, new): - o = {unicode_type(k) if isinstance(k, bytes) else k:set(v) if isinstance(v, list) else v for k, v in iteritems(o)} + o = {str(k) if isinstance(k, bytes) else k:set(v) if isinstance(v, list) else v for k, v in iteritems(o)} n = {k:set(v) if isinstance(v, list) else v for k, v in iteritems(n)} self.assertEqual(o, n) diff --git a/src/calibre/db/tests/writing.py b/src/calibre/db/tests/writing.py index 0d07e58797..1b17518a9f 100644 --- a/src/calibre/db/tests/writing.py +++ b/src/calibre/db/tests/writing.py @@ -15,7 +15,7 @@ from calibre.utils.date import UNDEFINED_DATE from calibre.db.tests.base import BaseTest, IMG from calibre.db.backend import FTSQueryError -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues class WritingTest(BaseTest): @@ -664,11 +664,11 @@ def test_dump_and_restore(self): # {{{ def test_set_author_data(self): # {{{ cache = self.init_cache() adata = cache.author_data() - ldata = {aid:unicode_type(aid) for aid in adata} + ldata = {aid:str(aid) for aid in adata} self.assertEqual({1,2,3}, cache.set_link_for_authors(ldata)) for c in (cache, self.init_cache()): self.assertEqual(ldata, {aid:d['link'] for aid, d in iteritems(c.author_data())}) - self.assertEqual({3}, cache.set_link_for_authors({aid:'xxx' if aid == max(adata) else unicode_type(aid) for aid in adata}), + self.assertEqual({3}, cache.set_link_for_authors({aid:'xxx' if aid == max(adata) else str(aid) for aid in adata}), 'Setting the author link to the same value as before, incorrectly marked some books as dirty') sdata = {aid:'%s, changed' % aid for aid in adata} self.assertEqual({1,2,3}, cache.set_sort_for_authors(sdata)) diff --git a/src/calibre/db/utils.py b/src/calibre/db/utils.py index d3c988665f..89b26bfa59 100644 --- a/src/calibre/db/utils.py +++ b/src/calibre/db/utils.py @@ -8,7 +8,7 @@ import os, errno, sys, re from locale import localeconv from collections import OrderedDict, namedtuple -from polyglot.builtins import iteritems, itervalues, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, itervalues, string_or_bytes from threading import Lock from calibre import as_unicode, prints @@ -18,7 +18,7 @@ def force_to_bool(val): - if isinstance(val, (bytes, unicode_type)): + if isinstance(val, (bytes, str)): if isinstance(val, bytes): val = val.decode(preferred_encoding, 'replace') try: @@ -227,7 +227,7 @@ def _apply_size(self): def _write_order(self): if hasattr(self, 'items'): try: - data = '\n'.join(group_id + ' ' + unicode_type(book_id) for (group_id, book_id) in self.items) + data = '\n'.join(group_id + ' ' + str(book_id) for (group_id, book_id) in self.items) with lopen(os.path.join(self.location, 'order'), 'wb') as f: f.write(data.encode('utf-8')) except EnvironmentError as err: diff --git a/src/calibre/db/view.py b/src/calibre/db/view.py index e9af22ccc3..8b00c10aa8 100644 --- a/src/calibre/db/view.py +++ b/src/calibre/db/view.py @@ -8,7 +8,7 @@ import weakref, operator, numbers from functools import partial -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from calibre.ebooks.metadata import title_sort from calibre.utils.config_base import tweaks, prefs @@ -376,7 +376,7 @@ def set_marked_ids(self, id_dict): self.marked_ids = dict.fromkeys(id_dict, u'true') else: # Ensure that all the items in the dict are text - self.marked_ids = {k: unicode_type(v) for k, v in iteritems(id_dict)} + self.marked_ids = {k: str(v) for k, v in iteritems(id_dict)} # This invalidates all searches in the cache even though the cache may # be shared by multiple views. This is not ideal, but... cmids = set(self.marked_ids) diff --git a/src/calibre/db/write.py b/src/calibre/db/write.py index d3beb31794..daaeb49c46 100644 --- a/src/calibre/db/write.py +++ b/src/calibre/db/write.py @@ -9,7 +9,7 @@ import re from functools import partial from datetime import datetime -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from calibre.constants import preferred_encoding from calibre.ebooks.metadata import author_to_author_sort, title_sort @@ -30,7 +30,7 @@ def sqlite_datetime(x): def single_text(x): if x is None: return x - if not isinstance(x, unicode_type): + if not isinstance(x, str): x = x.decode(preferred_encoding, 'replace') x = x.strip() return x if x else None @@ -58,7 +58,7 @@ def multiple_text(sep, ui_sep, x): return () if isinstance(x, bytes): x = x.decode(preferred_encoding, 'replace') - if isinstance(x, unicode_type): + if isinstance(x, str): x = x.split(sep) else: x = (y.decode(preferred_encoding, 'replace') if isinstance(y, bytes) @@ -70,7 +70,7 @@ def multiple_text(sep, ui_sep, x): def adapt_datetime(x): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): x = parse_date(x, assume_utc=False, as_utc=False) if x and is_date_undefined(x): x = UNDEFINED_DATE @@ -78,7 +78,7 @@ def adapt_datetime(x): def adapt_date(x): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): x = parse_only_date(x) if x is None or is_date_undefined(x): x = UNDEFINED_DATE @@ -88,7 +88,7 @@ def adapt_date(x): def adapt_number(typ, x): if x is None: return None - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = x.decode(preferred_encoding, 'replace') if not x or x.lower() == 'none': @@ -97,7 +97,7 @@ def adapt_number(typ, x): def adapt_bool(x): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = x.decode(preferred_encoding, 'replace') x = x.lower() diff --git a/src/calibre/debug.py b/src/calibre/debug.py index 899be70cdc..e85f11174f 100644 --- a/src/calibre/debug.py +++ b/src/calibre/debug.py @@ -12,7 +12,7 @@ from calibre.constants import iswindows from calibre import prints from calibre.startup import get_debug_executable -from polyglot.builtins import exec_path, unicode_type +from polyglot.builtins import exec_path def run_calibre_debug(*args, **kw): @@ -204,7 +204,7 @@ def print_basic_debug_info(out=None): out('Linux:', platform.linux_distribution()) except: pass - out('Interface language:', unicode_type(set_translators.lang)) + out('Interface language:', str(set_translators.lang)) from calibre.customize.ui import has_external_plugins, initialized_plugins if has_external_plugins(): from calibre.customize import PluginInstallationType diff --git a/src/calibre/devices/__init__.py b/src/calibre/devices/__init__.py index df5405255b..8d95c2f475 100644 --- a/src/calibre/devices/__init__.py +++ b/src/calibre/devices/__init__.py @@ -8,7 +8,6 @@ import sys, time, pprint from functools import partial -from polyglot.builtins import unicode_type DAY_MAP = dict(Sun=0, Mon=1, Tue=2, Wed=3, Thu=4, Fri=5, Sat=6) MONTH_MAP = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12) @@ -19,8 +18,8 @@ def strptime(src): src = src.strip() src = src.split() - src[0] = unicode_type(DAY_MAP[src[0][:-1]])+',' - src[2] = unicode_type(MONTH_MAP[src[2]]) + src[0] = str(DAY_MAP[src[0][:-1]])+',' + src[2] = str(MONTH_MAP[src[2]]) return time.strptime(' '.join(src), '%w, %d %m %Y %H:%M:%S %Z') diff --git a/src/calibre/devices/cli.py b/src/calibre/devices/cli.py index 46c7b8983a..46e771e4d4 100755 --- a/src/calibre/devices/cli.py +++ b/src/calibre/devices/cli.py @@ -17,7 +17,6 @@ from calibre.customize.ui import device_plugins from calibre.devices.scanner import DeviceScanner from calibre.utils.config import device_prefs -from polyglot.builtins import unicode_type from polyglot.io import PolyglotStringIO MINIMUM_COL_WIDTH = 12 # : Minimum width of columns in ls output @@ -125,7 +124,7 @@ def row_widths(table): # Calculate widths for each column in the row-wise table maxlen = 0 if ll: # Calculate column width for size column for file in files: - size = len(unicode_type(file.size)) + size = len(str(file.size)) if human_readable_size: file = FileFormatter(file) size = len(file.human_readable_size) @@ -137,10 +136,10 @@ def row_widths(table): # Calculate widths for each column in the row-wise table lsoutput.append(name) lscoloutput.append(name) if ll: - size = unicode_type(file.size) + size = str(file.size) if human_readable_size: size = file.human_readable_size - prints(file.mode_string, ("%"+unicode_type(maxlen)+"s")%size, file.modification_time, name, file=output) + prints(file.mode_string, ("%"+str(maxlen)+"s")%size, file.modification_time, name, file=output) if not ll and len(lsoutput) > 0: trytable = [] for colwidth in range(MINIMUM_COL_WIDTH, cols): @@ -244,7 +243,7 @@ def main(): print("Filesystem\tSize \tUsed \tAvail \tUse%") for i in range(3): print("%-10s\t%s\t%s\t%s\t%s"%(where[i], human_readable(total[i]), human_readable(total[i]-free[i]), human_readable(free[i]), - unicode_type(0 if total[i]==0 else int(100*(total[i]-free[i])/(total[i]*1.)))+"%")) + str(0 if total[i]==0 else int(100*(total[i]-free[i])/(total[i]*1.)))+"%")) elif command == 'eject': dev.eject() elif command == "books": diff --git a/src/calibre/devices/cybook/t2b.py b/src/calibre/devices/cybook/t2b.py index 48ad9bcb87..0eecc180ef 100644 --- a/src/calibre/devices/cybook/t2b.py +++ b/src/calibre/devices/cybook/t2b.py @@ -7,7 +7,7 @@ ''' import io -from polyglot.builtins import int_to_byte, unicode_type +from polyglot.builtins import int_to_byte DEFAULT_T2B_DATA = b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x0f\xff\xff\xff\xf0\xff\x0f\xc3\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf8\x00\x00\xff\xff\xff\xf0\xff\x0f\xc3\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xe0\xff\xf0\xff\xff\xff\xf0\xff\xff\xc3\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xc3\xff\xff\xff\xff\xff\xf0\xff\xff\xc3\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x07\xff\xff\xfc\x00?\xf0\xff\x0f\xc3\x00?\xf0\xc0\xfe\x00?\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff\xf0<\x0f\xf0\xff\x0f\xc0,\x0f\xf0\x0e\xf0,\x0f\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff\xff\xff\xc3\xf0\xff\x0f\xc0\xff\x0f\xf0\xff\xf0\xff\xc7\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff\xff\xff\xc3\xf0\xff\x0f\xc3\xff\xc3\xf0\xff\xc3\xff\xc3\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff\xff\x00\x03\xf0\xff\x0f\xc3\xff\xc3\xf0\xff\xc3\xff\xc3\xff\xff\xff\xff\xff\xff\xff\x0f\xff\xff\xf0\x1f\xc3\xf0\xff\x0f\xc3\xff\xc3\xf0\xff\xc0\x00\x03\xff\xff\xff\xff\xff\xff\xff\x0b\xff\xff\xf0\xff\xc3\xf0\xff\x0f\xc3\xff\xc3\xf0\xff\xc3\xff\xff\xff\xff\xff\xff\xff\xff\xff\xc3\xff\xff\xf3\xff\xc3\xf0\xff\x0f\xc3\xff\xc3\xf0\xff\xc3\xff\xff\xff\xff\xff\xff\xff\xff\xff\xc0\xff\xfc\xf0\xff\x03\xf0\xff\x0f\xc0\xff\x0f\xf0\xff\xf0\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf0\x0f\x00\xf08\x03\xf0\xff\x0f\xc0,\x0f\xf0\xff\xf0\x1f\x03\xff\xff\xff\xff\xff\xff\xff\xff\x00\x0f\xfc\x00\xc3\xf0\xff\x0f\xc3\x00?\xf0\xff\xff\x00\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf0\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xf0\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x03\xfe\x94\xff\xff\xff\xff\xff\xff\xff\xff\xff\xc0\x00\x00\x00\x0f\xff\xff\xff\xff\xff\xff\xfc\x7f\xfe\x94\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x0f\xff\xfe\xa9@\xff\xff\xff\xff\xff\xff\xfc?\xfe\xa4\xff\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xe9P\xff\xff\xff\xff\xff\xff\xfe/\xfe\xa8\xff\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xf9T\xff\xff\xff\xff\xf0@\x00+\xfa\xa8?\xff\xff\xff\xff\xff\xff\xff\xfc\xbf\xff\xff\xf9T\xff\xff\xff\xff\xcb\xe4}*\xaa\xaa?\xff\xff\xff\xff\xff\xff\xff\xfc\xbf\xff\xff\xe9T\xff\xff\xff\xff\xc7\xe4\xfd\x1a\xaa\xaa?\xff\xff\xff\xff\xff\xff\xff\xfc\xaf\xea\xaa\xa6\xa4\xff@\x00\x0f\xc3\xe8\xfe\x1a\xaa\xaa?\xff\xff\xff\xff\xff\xff\xff\xfcj\x95UZ\xa4\x00\x7f\xfe\x90\x03\xe8\xfe\n\xaa\xaa?\xff\xff\xff\xff\xff\xff\xff\xfcj\x95UZ\xa4?\xff\xff\xa5C\xe8\xfe\x06\xaa\xaa?\xff\xff\xff\xff\xff\xff\xff\xfcj\x95UZ\xa4?\xff\xff\xeaC\xe8\xbe\x06\xaa\xaa\x0f\xff\xff\xff\xff\xff\xff\xff\xfcj\x95UZ\xa4/\xff\xff\xea\x82\xe8j\x06\xaa\xaa\x0f\xff\xff\xff\xff\xff\xff\xff\xfcj\x95UZ\xa4/\xff\xff\xaa\x82\xe8*F\xaa\xaa\x8f\xff\xff\xff\xff\xff\xff\xff\xfcj\x95UZ\xa4+\xff\xfe\xaa\x82\xe8*\x86\xaa\xaa\x8f\xff\xff\x80\xff\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xe8*\x86\xaa\xaa\x8f\xf0\x00T?\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xe8*\x81\xaa\xaa\x8c\x03\xff\x95?\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xe8*\x81\xaa\xaa\x80\xbf\xff\x95?\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xe8*\x81\xaa\xaa\x9b\xff\xff\x95\x0f\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xe8\x1a\x81\xaa\xaa\x9a\xff\xfe\x95\x0f\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xe8\n\x81\xaa\xaa\xa6\xbf\xfeUO\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xa8\n\x91j\xaa\xa5\xaa\xa9ZO\xff\xff\xff\xfcj\x95UV\xa4\x1a\xfa\xaa\xaa\x82\xa8\n\xa0j\xaa\xa5Z\x95ZO\xff\xff\xff\xfcj\x95UV\xa4*\xfa\xaa\xaa\x82\xa9\n\xa0j\xaa\xa5UUZC\xff\xff\xff\xfcj\x95UV\xa4*\xfa\xaa\xaa\x82\xaa\n\xa0j\xaa\xa4UUZS\xff\xff\xff\xfcZ\x95UV\xa4*\xfa\xaa\xaa\x82\xaa\n\xa0j\xaa\xa4UUZS\xff\xff\xff\xfcZ\x95UU\xa4*\xfa\xaa\xaa\x82\xaa\n\xa0j\xaa\xa8UUVS\xff\xff\xff\xfcZ\x95UU\xa4*\xea\xaa\xaa\x82\xaa\x06\xa0Z\xaa\xa8UUV\x93\xff\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x81\xaa\x02\xa0\x1a\xaa\xa8UUV\x90\xff\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x80\xaa\x02\xa0\x1a\xaa\xa8\x15UU\x94\xff\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x80\xaa"\xa0\x1a\xaa\xa8\x15UU\x94\xff\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x80\xaa2\xa4\x16\xaa\xa8\x15UU\x94\xff\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x80\xaa2\xa8\x16\xa6\xa9\x15UU\x94\xff\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x80\xaa2\xa8\x16\xa6\xa9\x05UUT?\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x84\xaa2\xa8\x16\xaa\xaa\x05UUU?\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x88\xaa2\xa8\x06\xaa\xaa\x05UUU?\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa1\xa8\xc5\xaa\xaa\x05UUU?\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa0\xa8E\xa9\xaa\x05UUU/\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa<\xa8\x05\xa9\xaaAUUU\x0f\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa<\xa8\x05\xa9\xaaAUUUO\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa<\xa9\x05\xaa\xaaAUUUO\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x1c\xaa\x01\xaa\xaa\x81UUUO\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x0c\xaa\x01\xaa\xaa\x81UUUO\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x0c\xaa1j\xaa\x80UUUC\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x0cj1jj\x90UUUS\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x0c*1jj\x90UUUS\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaaL*1jj\xa0UUUS\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x8f* j\xaa\xa0\x15UUS\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x8f*@j\xaa\xa0\x15UUP\xff\xff\xfcZ\x95UU\xa4*\xaa\xaa\xaa\x8c\xaa\x8f*\x8cZ\xaa\xa1\x15UUT\xff\xff\xfcZ\x95UU\xa4j\xaa\xaa\xaa\x8c\xaa\x8f*\x8cZ\x9a\xa0\x15UUT\xff\xff\xfcZ\x95UU\xa4j\xaa\xaa\xaa\x8c\xaa\x8f*\x8cZ\x9a\xa0\x15UUT\xff\xff\xfcZ\x95UU\xa4j\xaa\xaa\xaa\x8c\xaa\x8f\x1a\x8cZ\x9a\xa4\x15UUT?\xff\xfcZ\x95UU\x94j\xaa\xaa\xaa\x8cj\x8f\n\x8cVj\xa4\x05UU\xa4?\xff\xfcVUUU\xa4j\xaa\xaa\xaa\x8cj\x8fJ\x8c\x16\xaa\xa8\xc5UZ\xa5?\xff\xfcUUUV\xa4j\xaa\xaa\xaa\x8cj\x8f\xca\x8f\x16\xaa\xa8\xc5V\xaa\xa5?\xff\xfcUj\xaa\xaa\xa4j\xaa\xaa\xaa\x8cj\x8f\xca\x8f\x1a\xaa\xa8\x05Z\xaaU?\xff\xfcV\xaa\xaa\xaa\xa5j\xaa\xaa\xaa\x8e*\x8f\xca\x83\x1a\xaa\xa4\x01eUU?\xff\xfcZ\xaa\xaa\xaa\xa5j\xaa\xaa\xaa\x8f*\x8f\xca\x83\x1a\xa5U\x01U\x00\x00\x0f\xff\xfcUUUUUZ\xaa\xaa\xaaO%\x8f\xc6\x93\x15\x00\x001@\x0f\xff\xff\xff\xfcP\x00\x00\x00\x15\x00\x00\x00\x00\x0f\x00\x07\xc0\x03\x00\xff\xff0\x1f\xff\xff\xff\xff\xfc\x00\xff\xff\xf8\x00?\xff\xff\xff\x0f?\xc7\xc3\xf7\x0f\xff\xff\xf1\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xff\xf4\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' # noqa @@ -24,7 +24,7 @@ def reduce_color(c): def i2b(n): - return "".join([unicode_type((n >> y) & 1) for y in range(1, -1, -1)]) + return "".join([str((n >> y) & 1) for y in range(1, -1, -1)]) def write_t2b(t2bfile, coverdata=None): diff --git a/src/calibre/devices/errors.py b/src/calibre/devices/errors.py index ce088eae2e..56af2a091d 100644 --- a/src/calibre/devices/errors.py +++ b/src/calibre/devices/errors.py @@ -8,7 +8,6 @@ G{classtree ProtocolError} """ -from polyglot.builtins import unicode_type class ProtocolError(Exception): @@ -95,7 +94,7 @@ class DeviceBusy(ProtocolError): def __init__(self, uerr=""): ProtocolError.__init__( self, "Device is in use by another application:" - "\nUnderlying error:" + unicode_type(uerr) + "\nUnderlying error:" + str(uerr) ) @@ -138,9 +137,9 @@ def __init__(self, query=None, response=None, desc=None): def __str__(self): if self.query and self.response: return "Got unexpected response:\n" + \ - "query:\n"+unicode_type(self.query.query)+"\n"+\ - "expected:\n"+unicode_type(self.query.response)+"\n" +\ - "actual:\n"+unicode_type(self.response) + "query:\n"+str(self.query.query)+"\n"+\ + "expected:\n"+str(self.query.response)+"\n" +\ + "actual:\n"+str(self.response) if self.desc: return self.desc return "Unknown control error occurred" diff --git a/src/calibre/devices/jetbook/driver.py b/src/calibre/devices/jetbook/driver.py index 0d476a9524..a047bdedad 100644 --- a/src/calibre/devices/jetbook/driver.py +++ b/src/calibre/devices/jetbook/driver.py @@ -15,7 +15,6 @@ from calibre.constants import filesystem_encoding from calibre.devices.usbms.driver import USBMS from calibre.ebooks.metadata import string_to_authors -from polyglot.builtins import unicode_type class JETBOOK(USBMS): @@ -65,7 +64,7 @@ def filename_callback(self, fname, mi): def metadata_from_path(cls, path): def check_unicode(txt): - if not isinstance(txt, unicode_type): + if not isinstance(txt, str): txt = txt.decode(filesystem_encoding, 'replace') txt = txt.replace('_', ' ') return txt diff --git a/src/calibre/devices/kindle/apnx.py b/src/calibre/devices/kindle/apnx.py index 7fdeea5951..36acd431f0 100644 --- a/src/calibre/devices/kindle/apnx.py +++ b/src/calibre/devices/kindle/apnx.py @@ -18,7 +18,7 @@ from calibre.utils.logging import default_log from calibre import prints, fsync from calibre.constants import DEBUG -from polyglot.builtins import as_unicode, as_bytes, unicode_type +from polyglot.builtins import as_unicode, as_bytes class APNXBuilder: @@ -33,7 +33,7 @@ def write_apnx(self, mobi_file_path, apnx_path, method=None, page_count=0): using either the fast or accurate algorithm. ''' import uuid - apnx_meta = {'guid': unicode_type(uuid.uuid4()).replace('-', '')[:8], 'asin': + apnx_meta = {'guid': str(uuid.uuid4()).replace('-', '')[:8], 'asin': '', 'cdetype': 'EBOK', 'format': 'MOBI_7', 'acr': ''} with lopen(mobi_file_path, 'rb') as mf: @@ -53,11 +53,11 @@ def write_apnx(self, mobi_file_path, apnx_path, method=None, page_count=0): if mh.exth is None or not mh.exth.cdetype: apnx_meta['cdetype'] = 'EBOK' else: - apnx_meta['cdetype'] = unicode_type(mh.exth.cdetype) + apnx_meta['cdetype'] = str(mh.exth.cdetype) if mh.exth is None or not mh.exth.uuid: apnx_meta['asin'] = '' else: - apnx_meta['asin'] = unicode_type(mh.exth.uuid) + apnx_meta['asin'] = str(mh.exth.uuid) # Get the pages depending on the chosen parser pages = [] diff --git a/src/calibre/devices/kindle/driver.py b/src/calibre/devices/kindle/driver.py index 4a5b9e117f..afbfc7c6d7 100644 --- a/src/calibre/devices/kindle/driver.py +++ b/src/calibre/devices/kindle/driver.py @@ -15,7 +15,7 @@ from calibre.devices.kindle.bookmark import Bookmark from calibre.devices.usbms.driver import USBMS from calibre import strftime, fsync, prints -from polyglot.builtins import unicode_type, as_bytes, as_unicode +from polyglot.builtins import as_bytes, as_unicode ''' Notes on collections: @@ -610,7 +610,7 @@ def upload_apnx(self, path, filename, metadata, filepath): cust_col_name = opts.extra_customization[self.OPT_APNX_METHOD_COL] if cust_col_name: try: - temp = unicode_type(metadata.get(cust_col_name)).lower() + temp = str(metadata.get(cust_col_name)).lower() if temp in self.EXTRA_CUSTOMIZATION_CHOICES[self.OPT_APNX_METHOD]: method = temp else: diff --git a/src/calibre/devices/kobo/driver.py b/src/calibre/devices/kobo/driver.py index 60ecc209e2..7f815751db 100644 --- a/src/calibre/devices/kobo/driver.py +++ b/src/calibre/devices/kobo/driver.py @@ -33,7 +33,7 @@ from calibre.ptempfile import PersistentTemporaryFile, better_mktemp from calibre.constants import DEBUG from calibre.utils.config_base import prefs -from polyglot.builtins import iteritems, itervalues, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, itervalues, string_or_bytes EPUB_EXT = '.epub' KEPUB_EXT = '.kepub' @@ -47,7 +47,7 @@ def qhash(inputstr): instr = b"" if isinstance(inputstr, bytes): instr = inputstr - elif isinstance(inputstr, unicode_type): + elif isinstance(inputstr, str): instr = inputstr.encode("utf8") else: return -1 @@ -377,7 +377,7 @@ def update_booklist(prefix, path, title, authors, mime, date, ContentType, Image try: cursor.execute(query) except Exception as e: - err = unicode_type(e) + err = str(e) if not (any_in(err, '___ExpirationStatus', 'FavouritesIndex', 'Accessibility', 'IsDownloaded')): raise query= ('select Title, Attribution, DateCreated, ContentID, MimeType, ContentType, ' @@ -483,13 +483,13 @@ def delete_via_sql(self, ContentID, ContentType): cursor.execute('update content set ReadStatus=0, FirstTimeReading = \'true\', ___PercentRead=0, ___ExpirationStatus=3 ' 'where BookID is Null and ContentID =?',t) except Exception as e: - if 'no such column' not in unicode_type(e): + if 'no such column' not in str(e): raise try: cursor.execute('update content set ReadStatus=0, FirstTimeReading = \'true\', ___PercentRead=0 ' 'where BookID is Null and ContentID =?',t) except Exception as e: - if 'no such column' not in unicode_type(e): + if 'no such column' not in str(e): raise cursor.execute('update content set ReadStatus=0, FirstTimeReading = \'true\' ' 'where BookID is Null and ContentID =?',t) @@ -833,7 +833,7 @@ def reset_favouritesindex(self, connection, oncard): cursor.execute(query) except Exception as e: debug_print(' Database Exception: Unable to reset Shortlist list') - if 'no such column' not in unicode_type(e): + if 'no such column' not in str(e): raise finally: cursor.close() @@ -847,7 +847,7 @@ def set_favouritesindex(self, connection, ContentID): cursor.execute('update content set FavouritesIndex=1 where BookID is Null and ContentID = ?', t) except Exception as e: debug_print(' Database Exception: Unable set book as Shortlist') - if 'no such column' not in unicode_type(e): + if 'no such column' not in str(e): raise finally: cursor.close() @@ -1808,7 +1808,7 @@ def update_booklist(prefix, path, ContentID, ContentType, MimeType, ImageID, debug_print('KoboTouch:update_booklist - book file does not exist. ContentID="%s"'%ContentID) except Exception as e: - debug_print("KoboTouch:update_booklist - exception creating book: '%s'"%unicode_type(e)) + debug_print("KoboTouch:update_booklist - exception creating book: '%s'"%str(e)) debug_print(" prefix: ", prefix, "lpath: ", lpath, "title: ", title, "authors: ", authors, "MimeType: ", MimeType, "DateCreated: ", DateCreated, "ContentType: ", ContentType, "ImageID: ", ImageID) raise @@ -1870,7 +1870,7 @@ def get_bookshelvesforbook(connection, ContentID): bookshelves.append(row['ShelfName']) cursor.close() -# debug_print("KoboTouch:get_bookshelvesforbook - count bookshelves=" + unicode_type(count_bookshelves)) +# debug_print("KoboTouch:get_bookshelvesforbook - count bookshelves=" + str(count_bookshelves)) return bookshelves self.debug_index = 0 @@ -1963,7 +1963,7 @@ def get_bookshelvesforbook(connection, ContentID): try: cursor.execute(query) except Exception as e: - err = unicode_type(e) + err = str(e) if not (any_in(err, '___ExpirationStatus', 'FavouritesIndex', 'Accessibility', 'IsDownloaded', 'Series', 'ExternalId')): raise query= ('SELECT Title, Attribution, DateCreated, ContentID, MimeType, ContentType, ' @@ -2174,7 +2174,7 @@ def upload_books(self, files, names, on_card=None, end_session=True, cursor.close() except Exception as e: - debug_print('KoboTouch:upload_books - Exception: %s'%unicode_type(e)) + debug_print('KoboTouch:upload_books - Exception: %s'%str(e)) return result @@ -2318,7 +2318,7 @@ def delete_via_sql(self, ContentID, ContentType): debug_print('KoboTouch:delete_via_sql: finished SQL') debug_print('KoboTouch:delete_via_sql: After SQL, no exception') except Exception as e: - debug_print('KoboTouch:delete_via_sql - Database Exception: %s'%unicode_type(e)) + debug_print('KoboTouch:delete_via_sql - Database Exception: %s'%str(e)) debug_print('KoboTouch:delete_via_sql: imageId="%s"'%imageId) if imageId is None: @@ -2451,7 +2451,7 @@ def update_device_database_collections(self, booklists, collections_attributes, if self.manage_collections: if collections: - # debug_print("KoboTouch:update_device_database_collections - length collections=" + unicode_type(len(collections))) + # debug_print("KoboTouch:update_device_database_collections - length collections=" + str(len(collections))) # Need to reset the collections outside the particular loops # otherwise the last item will not be removed @@ -2621,7 +2621,7 @@ def upload_cover(self, path, filename, metadata, filepath): self.keep_cover_aspect, self.letterbox_fs_covers, self.png_covers, letterbox_color=self.letterbox_fs_covers_color) except Exception as e: - debug_print('KoboTouch: FAILED to upload cover=%s Exception=%s'%(filepath, unicode_type(e))) + debug_print('KoboTouch: FAILED to upload cover=%s Exception=%s'%(filepath, str(e))) def imageid_from_contentid(self, ContentID): ImageID = ContentID.replace('/', '_') @@ -2831,7 +2831,7 @@ def _upload_cover( f.write(data) fsync(f) except Exception as e: - err = unicode_type(e) + err = str(e) debug_print("KoboTouch:_upload_cover - Exception string: %s"%err) raise @@ -2978,7 +2978,7 @@ def get_bookshelflist(self, connection): # count_bookshelves = i + 1 cursor.close() -# debug_print("KoboTouch:get_bookshelflist - count bookshelves=" + unicode_type(count_bookshelves)) +# debug_print("KoboTouch:get_bookshelflist - count bookshelves=" + str(count_bookshelves)) return bookshelves @@ -3062,7 +3062,7 @@ def check_for_bookshelf(self, connection, bookshelf_name): cursor.execute(addquery, add_values) elif result['_IsDeleted'] == 'true': debug_print("KoboTouch:check_for_bookshelf - Shelf '%s' is deleted - undeleting. result['_IsDeleted']='%s'" % ( - bookshelf_name, unicode_type(result['_IsDeleted']))) + bookshelf_name, str(result['_IsDeleted']))) cursor.execute(updatequery, test_values) cursor.close() diff --git a/src/calibre/devices/kobo/kobotouch_config.py b/src/calibre/devices/kobo/kobotouch_config.py index 046bb8afb5..f08d1ecbb6 100644 --- a/src/calibre/devices/kobo/kobotouch_config.py +++ b/src/calibre/devices/kobo/kobotouch_config.py @@ -16,7 +16,6 @@ from calibre.gui2 import error_dialog from calibre.gui2.widgets2 import ColorButton from calibre.gui2.dialogs.template_dialog import TemplateDialog -from polyglot.builtins import unicode_type def wrap_msg(msg): @@ -128,7 +127,7 @@ def commit(self): p['support_newer_firmware'] = self.support_newer_firmware p['debugging_title'] = self.debugging_title - p['driver_version'] = '.'.join([unicode_type(i) for i in self.device.version]) + p['driver_version'] = '.'.join([str(i) for i in self.device.version]) return p @@ -480,7 +479,7 @@ def __init__(self, parent, device): 'to perform full read-write functionality - Here be Dragons!! ' 'Enable only if you are comfortable with restoring your kobo ' 'to factory defaults and testing software. ' - 'This driver supports firmware V2.x.x and DBVersion up to ') + unicode_type( + 'This driver supports firmware V2.x.x and DBVersion up to ') + str( device.supported_dbversion), device.get_pref('support_newer_firmware') ) @@ -638,7 +637,7 @@ def __init__(self, val, tooltip=None): @property def template(self): - return unicode_type(self.t.text()).strip() + return str(self.t.text()).strip() @template.setter def template(self, template): @@ -660,7 +659,7 @@ def validate(self): except Exception as err: error_dialog(self, _('Invalid template'), '

'+_('The template "%s" is invalid:')%tmpl + - '
'+unicode_type(err), show=True) + '
'+str(err), show=True) return False # }}} diff --git a/src/calibre/devices/mtp/driver.py b/src/calibre/devices/mtp/driver.py index 1f709ce445..54276b55a2 100644 --- a/src/calibre/devices/mtp/driver.py +++ b/src/calibre/devices/mtp/driver.py @@ -16,7 +16,7 @@ from calibre.devices.mtp.defaults import DeviceDefaults from calibre.ptempfile import SpooledTemporaryFile, PersistentTemporaryDirectory from calibre.utils.filenames import shorten_components_to -from polyglot.builtins import iteritems, itervalues, unicode_type, as_bytes +from polyglot.builtins import iteritems, itervalues, as_bytes BASE = importlib.import_module('calibre.devices.mtp.%s.driver'%( 'windows' if iswindows else 'unix')).MTP_DEVICE @@ -76,7 +76,7 @@ def prefs(self): def is_folder_ignored(self, storage_or_storage_id, path, ignored_folders=None): - storage_id = unicode_type(getattr(storage_or_storage_id, 'object_id', + storage_id = str(getattr(storage_or_storage_id, 'object_id', storage_or_storage_id)) lpath = tuple(icu_lower(name) for name in path) if ignored_folders is None: @@ -168,14 +168,14 @@ def _update_drive_info(self, storage, location_code, name=None): traceback.print_exc() dinfo = {} if dinfo.get('device_store_uuid', None) is None: - dinfo['device_store_uuid'] = unicode_type(uuid.uuid4()) + dinfo['device_store_uuid'] = str(uuid.uuid4()) if dinfo.get('device_name', None) is None: dinfo['device_name'] = self.current_friendly_name if name is not None: dinfo['device_name'] = name dinfo['location_code'] = location_code dinfo['last_library_uuid'] = getattr(self, 'current_library_uuid', None) - dinfo['calibre_version'] = '.'.join([unicode_type(i) for i in numeric_version]) + dinfo['calibre_version'] = '.'.join([str(i) for i in numeric_version]) dinfo['date_last_connected'] = isoformat(now()) dinfo['mtp_prefix'] = storage.storage_prefix raw = as_bytes(json.dumps(dinfo, default=to_json)) diff --git a/src/calibre/devices/mtp/filesystem_cache.py b/src/calibre/devices/mtp/filesystem_cache.py index f5c5a4539d..62ef4fe98e 100644 --- a/src/calibre/devices/mtp/filesystem_cache.py +++ b/src/calibre/devices/mtp/filesystem_cache.py @@ -9,7 +9,7 @@ import weakref, sys, json from collections import deque from operator import attrgetter -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues from datetime import datetime from calibre import human_readable, prints, force_unicode @@ -73,7 +73,7 @@ def __init__(self, entry, fs_cache): def __repr__(self): name = 'Folder' if self.is_folder else 'File' try: - path = unicode_type(self.full_path) + path = str(self.full_path) except: path = '' datum = 'size=%s'%(self.size) diff --git a/src/calibre/devices/mtp/unix/driver.py b/src/calibre/devices/mtp/unix/driver.py index 2343f8d964..3038a2c727 100644 --- a/src/calibre/devices/mtp/unix/driver.py +++ b/src/calibre/devices/mtp/unix/driver.py @@ -15,7 +15,6 @@ from calibre.ptempfile import SpooledTemporaryFile from calibre.devices.errors import OpenFailed, DeviceError, BlacklistedDevice, OpenActionNeeded from calibre.devices.mtp.base import MTPDeviceBase, synchronous, debug -from polyglot.builtins import unicode_type MTPDevice = namedtuple('MTPDevice', 'busnum devnum vendor_id product_id ' 'bcd serial manufacturer product') @@ -222,7 +221,7 @@ def open(self, connected_device, library_uuid): try: storage = sorted(self.dev.storage_info, key=operator.itemgetter('id')) except self.libmtp.MTPError as e: - if "The device has no storage information." in unicode_type(e): + if "The device has no storage information." in str(e): # This happens on newer Android devices while waiting for # the user to allow access. Apparently what happens is # that when the user clicks allow, the device disconnects @@ -317,7 +316,7 @@ def filesystem_cache(self): storage.append({'id':sid, 'size':capacity, 'is_folder':True, 'name':name, 'can_delete':False, 'is_system':True}) - self._currently_getting_sid = unicode_type(sid) + self._currently_getting_sid = str(sid) items, errs = self.dev.get_filesystem(sid, partial(self._filesystem_callback, {})) all_items.extend(items), all_errs.extend(errs) diff --git a/src/calibre/devices/mtp/windows/driver.py b/src/calibre/devices/mtp/windows/driver.py index 73a592c662..3bfbe1f451 100644 --- a/src/calibre/devices/mtp/windows/driver.py +++ b/src/calibre/devices/mtp/windows/driver.py @@ -8,7 +8,7 @@ import time, threading, traceback from functools import wraps, partial -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from itertools import chain from calibre import as_unicode, prints, force_unicode @@ -268,7 +268,7 @@ def filesystem_cache(self): break storage = {'id':storage_id, 'size':capacity, 'name':name, 'is_folder':True, 'can_delete':False, 'is_system':True} - self._currently_getting_sid = unicode_type(storage_id) + self._currently_getting_sid = str(storage_id) id_map = self.dev.get_filesystem(storage_id, partial( self._filesystem_callback, {})) for x in itervalues(id_map): diff --git a/src/calibre/devices/prs505/sony_cache.py b/src/calibre/devices/prs505/sony_cache.py index 718c3fd5fa..00a05d8197 100644 --- a/src/calibre/devices/prs505/sony_cache.py +++ b/src/calibre/devices/prs505/sony_cache.py @@ -17,7 +17,6 @@ from calibre.ebooks.metadata import authors_to_string, title_sort, \ authors_to_sort_string from polyglot.binary import from_base64_bytes -from polyglot.builtins import unicode_type ''' cacheExt.xml @@ -66,8 +65,8 @@ def strptime(src): src = src.strip() src = src.split() - src[0] = unicode_type(DAY_MAP[src[0][:-1]])+',' - src[2] = unicode_type(MONTH_MAP[src[2]]) + src[0] = str(DAY_MAP[src[0][:-1]])+',' + src[2] = str(MONTH_MAP[src[2]]) return time.strptime(' '.join(src), '%w, %d %m %Y %H:%M:%S %Z') @@ -84,7 +83,7 @@ def strftime(epoch, zone=time.localtime): def uuid(): from uuid import uuid4 - return unicode_type(uuid4()).replace('-', '', 1).upper() + return str(uuid4()).replace('-', '', 1).upper() # }}} @@ -197,8 +196,8 @@ def ensure_unique_playlist_titles(self): playlist.set('title', title) if title in seen: for i in range(2, 1000): - if title+unicode_type(i) not in seen: - title = title+unicode_type(i) + if title+str(i) not in seen: + title = title+str(i) playlist.set('title', title) seen.add(title) break @@ -271,7 +270,7 @@ def get_or_create_playlist(self, bl_idx, title): nsmap=root.nsmap, attrib={ 'uuid' : uuid(), 'title': title, - 'id' : unicode_type(self.max_id(root)+1), + 'id' : str(self.max_id(root)+1), 'sourceid': '1' }) root.append(ans) @@ -310,13 +309,13 @@ def remap_playlist_references(root, idmap): def ensure_media_xml_base_ids(root): for num, tag in enumerate(('library', 'watchSpecial')): for x in root.xpath('//*[local-name()="%s"]'%tag): - x.set('id', unicode_type(num)) + x.set('id', str(num)) def rebase_ids(root, base, sourceid, pl_sourceid): 'Rebase all ids and also make them consecutive' for item in root.xpath('//*[@sourceid]'): sid = pl_sourceid if item.tag.endswith('playlist') else sourceid - item.set('sourceid', unicode_type(sid)) + item.set('sourceid', str(sid)) # Only rebase ids of nodes that are immediate children of the # record root (that way playlist/itemnodes are unaffected items = root.xpath('child::*[@id]') @@ -326,8 +325,8 @@ def rebase_ids(root, base, sourceid, pl_sourceid): old = int(item.get('id')) new = base + i if old != new: - item.set('id', unicode_type(new)) - idmap[unicode_type(old)] = unicode_type(new) + item.set('id', str(new)) + idmap[str(old)] = str(new) return idmap self.prune_empty_playlists() @@ -356,7 +355,7 @@ def rebase_ids(root, base, sourceid, pl_sourceid): last_bl = max(self.roots.keys()) max_id = self.max_id(self.roots[last_bl]) - self.roots[0].set('nextID', unicode_type(max_id+1)) + self.roots[0].set('nextID', str(max_id+1)) debug_print('Finished running fix_ids()') # }}} @@ -513,7 +512,7 @@ def update_playlists(self, bl_index, root, booklist, collections_attributes): # Ensure each book has an ID. for rec in records: if rec.get('id', None) is None: - rec.set('id', unicode_type(self.max_id(root)+1)) + rec.set('id', str(self.max_id(root)+1)) ids = [x.get('id', None) for x in records] # Given that we set the ids, there shouldn't be any None's. But # better to be safe... @@ -570,7 +569,7 @@ def create_text_record(self, root, bl_id, lpath): id_ = self.max_id(root)+1 attrib = { 'page':'0', 'part':'0','pageOffset':'0','scale':'0', - 'id':unicode_type(id_), 'sourceid':'1', 'path':lpath} + 'id':str(id_), 'sourceid':'1', 'path':lpath} ans = root.makeelement('{%s}text'%namespace, attrib=attrib, nsmap=root.nsmap) root.append(ans) return ans @@ -589,7 +588,7 @@ def create_ext_text_record(self, root, bl_id, lpath, thumbnail): if thumbnail and thumbnail[-1]: ans.text = '\n' + '\t\t' t = root.makeelement('{%s}thumbnail'%namespace, - attrib={'width':unicode_type(thumbnail[0]), 'height':unicode_type(thumbnail[1])}, + attrib={'width':str(thumbnail[0]), 'height':str(thumbnail[1])}, nsmap=root.nsmap) t.text = 'main_thumbnail.jpg' ans.append(t) @@ -658,7 +657,7 @@ def record_set(k, v): date = strftime(timestamp, zone=tz) record.set('date', clean(date)) try: - record.set('size', clean(unicode_type(os.stat(path).st_size))) + record.set('size', clean(str(os.stat(path).st_size))) except: record.set('size', '0') title = book.title if book.title else _('Unknown') @@ -688,7 +687,7 @@ def record_set(k, v): record.set('sourceid', '1') if 'id' not in record.attrib: num = self.max_id(record.getroottree().getroot()) - record.set('id', unicode_type(num+1)) + record.set('id', str(num+1)) return (gtz_count, ltz_count, use_tz_var) # }}} diff --git a/src/calibre/devices/prst1/driver.py b/src/calibre/devices/prst1/driver.py index a46bc469b2..97adc71bde 100644 --- a/src/calibre/devices/prst1/driver.py +++ b/src/calibre/devices/prst1/driver.py @@ -23,7 +23,7 @@ from calibre.devices.usbms.books import BookList from calibre.ebooks.metadata import authors_to_sort_string, authors_to_string from calibre.constants import islinux -from polyglot.builtins import unicode_type, long_type +from polyglot.builtins import long_type DBPATH = 'Sony_Reader/database/books.db' THUMBPATH = 'Sony_Reader/database/cache/books/%s/thumbnail/main_thumbnail.jpg' @@ -170,7 +170,7 @@ def books(self, oncard=None, end_session=True): with closing(sqlite.connect(dbpath)) as connection: # Replace undecodable characters in the db instead of erroring out - connection.text_factory = lambda x: x if isinstance(x, unicode_type) else x.decode('utf-8', 'replace') + connection.text_factory = lambda x: x if isinstance(x, str) else x.decode('utf-8', 'replace') cursor = connection.cursor() # Query collections diff --git a/src/calibre/devices/smart_device_app/driver.py b/src/calibre/devices/smart_device_app/driver.py index 6a2fa5f937..db4fe5cb45 100644 --- a/src/calibre/devices/smart_device_app/driver.py +++ b/src/calibre/devices/smart_device_app/driver.py @@ -47,7 +47,7 @@ ) from calibre.utils.socket_inheritance import set_socket_inherit from polyglot import queue -from polyglot.builtins import as_bytes, iteritems, itervalues, unicode_type +from polyglot.builtins import as_bytes, iteritems, itervalues def synchronous(tlockname): @@ -125,13 +125,13 @@ def run(self): content_server_port = '' try: from calibre.srv.opts import server_config - content_server_port = unicode_type(server_config().port) + content_server_port = str(server_config().port) except Exception: pass message = (self.driver.ZEROCONF_CLIENT_STRING + ' (on ' + - unicode_type(socket.gethostname().partition('.')[0]) + + str(socket.gethostname().partition('.')[0]) + ');' + content_server_port + - ',' + unicode_type(self.driver.port)).encode('utf-8') + ',' + str(self.driver.port)).encode('utf-8') self.driver._debug('received broadcast', packet, message) self.driver.broadcast_socket.sendto(message, remote) except: @@ -414,7 +414,7 @@ def _debug(self, *args): if isinstance(a, dict): printable = {} for k,v in iteritems(a): - if isinstance(v, (bytes, unicode_type)) and len(v) > 50: + if isinstance(v, (bytes, str)) and len(v) > 50: printable[k] = 'too long' else: printable[k] = v @@ -436,14 +436,14 @@ def _update_driveinfo_record(self, dinfo, prefix, location_code, name=None): if not isinstance(dinfo, dict): dinfo = {} if dinfo.get('device_store_uuid', None) is None: - dinfo['device_store_uuid'] = unicode_type(uuid.uuid4()) + dinfo['device_store_uuid'] = str(uuid.uuid4()) if dinfo.get('device_name') is None: dinfo['device_name'] = self.get_gui_name() if name is not None: dinfo['device_name'] = name dinfo['location_code'] = location_code dinfo['last_library_uuid'] = getattr(self, 'current_library_uuid', None) - dinfo['calibre_version'] = '.'.join([unicode_type(i) for i in numeric_version]) + dinfo['calibre_version'] = '.'.join([str(i) for i in numeric_version]) dinfo['date_last_connected'] = isoformat(now()) dinfo['prefix'] = self.PREFIX return dinfo @@ -495,9 +495,9 @@ def _create_upload_path(self, mdata, fname, create_dirs=True): from calibre.library.save_to_disk import config, get_components opts = config().parse() - if not isinstance(template, unicode_type): + if not isinstance(template, str): template = template.decode('utf-8') - app_id = unicode_type(getattr(mdata, 'application_id', '')) + app_id = str(getattr(mdata, 'application_id', '')) id_ = mdata.get('id', fname) extra_components = get_components(template, mdata, id_, timefmt=opts.send_timefmt, length=maxlen-len(app_id)-1, @@ -747,7 +747,7 @@ def _metadata_in_cache(self, uuid, ext_or_lpath, lastmod): from calibre.utils.date import now, parse_date try: key = self._make_metadata_cache_key(uuid, ext_or_lpath) - if isinstance(lastmod, unicode_type): + if isinstance(lastmod, str): if lastmod == 'None': return None lastmod = parse_date(lastmod) @@ -1909,7 +1909,7 @@ def _startup_on_demand(self): 'between 50 and 99. Forced to be %d.')%self.DEFAULT_THUMBNAIL_COMPRESSION_QUALITY self._debug(message) self.set_option('thumbnail_compression_quality', - unicode_type(self.DEFAULT_THUMBNAIL_COMPRESSION_QUALITY)) + str(self.DEFAULT_THUMBNAIL_COMPRESSION_QUALITY)) try: self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) diff --git a/src/calibre/devices/usbms/deviceconfig.py b/src/calibre/devices/usbms/deviceconfig.py index f915f15f55..0f61f7dc47 100644 --- a/src/calibre/devices/usbms/deviceconfig.py +++ b/src/calibre/devices/usbms/deviceconfig.py @@ -6,7 +6,6 @@ __docformat__ = 'restructuredtext en' from calibre.utils.config_base import Config, ConfigProxy -from polyglot.builtins import unicode_type class DeviceConfig: @@ -109,15 +108,15 @@ def save_settings(cls, config_widget): if hasattr(config_widget.opt_extra_customization[i], 'isChecked'): ec.append(config_widget.opt_extra_customization[i].isChecked()) elif hasattr(config_widget.opt_extra_customization[i], 'currentText'): - ec.append(unicode_type(config_widget.opt_extra_customization[i].currentText()).strip()) + ec.append(str(config_widget.opt_extra_customization[i].currentText()).strip()) else: - ec.append(unicode_type(config_widget.opt_extra_customization[i].text()).strip()) + ec.append(str(config_widget.opt_extra_customization[i].text()).strip()) else: - ec = unicode_type(config_widget.opt_extra_customization.text()).strip() + ec = str(config_widget.opt_extra_customization.text()).strip() if not ec: ec = None proxy['extra_customization'] = ec - st = unicode_type(config_widget.opt_save_template.text()) + st = str(config_widget.opt_save_template.text()) proxy['save_template'] = st @classmethod diff --git a/src/calibre/devices/usbms/driver.py b/src/calibre/devices/usbms/driver.py index 7664b2f699..afa2a212e0 100644 --- a/src/calibre/devices/usbms/driver.py +++ b/src/calibre/devices/usbms/driver.py @@ -21,7 +21,7 @@ from calibre.devices.usbms.device import Device from calibre.devices.usbms.books import BookList, Book from calibre.ebooks.metadata.book.json_codec import JsonCodec -from polyglot.builtins import itervalues, unicode_type, string_or_bytes +from polyglot.builtins import itervalues, string_or_bytes def debug_print(*args, **kw): @@ -107,14 +107,14 @@ def _update_driveinfo_record(self, dinfo, prefix, location_code, name=None): if not isinstance(dinfo, dict): dinfo = {} if dinfo.get('device_store_uuid', None) is None: - dinfo['device_store_uuid'] = unicode_type(uuid.uuid4()) + dinfo['device_store_uuid'] = str(uuid.uuid4()) if dinfo.get('device_name', None) is None: dinfo['device_name'] = self.get_gui_name() if name is not None: dinfo['device_name'] = name dinfo['location_code'] = location_code dinfo['last_library_uuid'] = getattr(self, 'current_library_uuid', None) - dinfo['calibre_version'] = '.'.join([unicode_type(i) for i in numeric_version]) + dinfo['calibre_version'] = '.'.join([str(i) for i in numeric_version]) dinfo['date_last_connected'] = isoformat(now()) dinfo['prefix'] = prefix.replace('\\', '/') return dinfo diff --git a/src/calibre/devices/utils.py b/src/calibre/devices/utils.py index 0cb0ad1bd9..16b740e2c8 100644 --- a/src/calibre/devices/utils.py +++ b/src/calibre/devices/utils.py @@ -10,7 +10,6 @@ from functools import partial from calibre.devices.errors import DeviceError, WrongDestinationError, FreeSpaceError -from polyglot.builtins import unicode_type def sanity_check(on_card, files, card_prefixes, free_space): @@ -97,9 +96,9 @@ def create_upload_path(mdata, fname, template, sanitize, ext = path_type.splitext(fname)[1] opts = config().parse() - if not isinstance(template, unicode_type): + if not isinstance(template, str): template = template.decode('utf-8') - app_id = unicode_type(getattr(mdata, 'application_id', '')) + app_id = str(getattr(mdata, 'application_id', '')) id_ = mdata.get('id', fname) extra_components = get_components(template, mdata, id_, timefmt=opts.send_timefmt, length=maxlen-len(app_id)-1, diff --git a/src/calibre/ebooks/BeautifulSoup.py b/src/calibre/ebooks/BeautifulSoup.py index ac445ad6b6..e297330f4d 100644 --- a/src/calibre/ebooks/BeautifulSoup.py +++ b/src/calibre/ebooks/BeautifulSoup.py @@ -9,13 +9,12 @@ SoupStrainer, Tag, __version__ ) -from polyglot.builtins import unicode_type def parse_html(markup): from calibre.ebooks.chardet import strip_encoding_declarations, xml_to_unicode, substitute_entites from calibre.utils.cleantext import clean_xml_chars - if isinstance(markup, unicode_type): + if isinstance(markup, str): markup = strip_encoding_declarations(markup) markup = substitute_entites(markup) else: diff --git a/src/calibre/ebooks/__init__.py b/src/calibre/ebooks/__init__.py index ab2260345e..f30f6e9daa 100644 --- a/src/calibre/ebooks/__init__.py +++ b/src/calibre/ebooks/__init__.py @@ -11,7 +11,6 @@ import os, re, numbers, sys from calibre import prints from calibre.ebooks.chardet import xml_to_unicode -from polyglot.builtins import unicode_type class ConversionError(Exception): @@ -82,7 +81,7 @@ def extract_calibre_cover(raw, base, log): if matches is None: body = soup.find('body') if body is not None: - text = u''.join(map(unicode_type, body.findAll(text=True))) + text = u''.join(map(str, body.findAll(text=True))) if text.strip(): # Body has text, abort return @@ -152,7 +151,7 @@ def check_ebook_format(stream, current_guess): def normalize(x): - if isinstance(x, unicode_type): + if isinstance(x, str): import unicodedata x = unicodedata.normalize('NFC', x) return x diff --git a/src/calibre/ebooks/chardet.py b/src/calibre/ebooks/chardet.py index b17290b657..47fb91a8e0 100644 --- a/src/calibre/ebooks/chardet.py +++ b/src/calibre/ebooks/chardet.py @@ -7,7 +7,6 @@ __docformat__ = 'restructuredtext en' import re, codecs, sys -from polyglot.builtins import unicode_type _encoding_pats = ( # XML declaration @@ -140,7 +139,7 @@ def force_encoding(raw, verbose, assume_utf8=False): def detect_xml_encoding(raw, verbose=False, assume_utf8=False): - if not raw or isinstance(raw, unicode_type): + if not raw or isinstance(raw, str): return raw, None for x in ('utf8', 'utf-16-le', 'utf-16-be'): bom = getattr(codecs, 'BOM_'+x.upper().replace('-16', '16').replace( @@ -184,7 +183,7 @@ def xml_to_unicode(raw, verbose=False, strip_encoding_pats=False, return '', None raw, encoding = detect_xml_encoding(raw, verbose=verbose, assume_utf8=assume_utf8) - if not isinstance(raw, unicode_type): + if not isinstance(raw, str): raw = raw.decode(encoding, 'replace') if strip_encoding_pats: diff --git a/src/calibre/ebooks/chm/reader.py b/src/calibre/ebooks/chm/reader.py index 6d2f2f0da4..2feb362a5a 100644 --- a/src/calibre/ebooks/chm/reader.py +++ b/src/calibre/ebooks/chm/reader.py @@ -13,7 +13,7 @@ from calibre.ebooks.chardet import xml_to_unicode from calibre.ebooks.metadata.toc import TOC from chm.chm import CHMFile, chmlib -from polyglot.builtins import as_unicode, unicode_type +from polyglot.builtins import as_unicode def match_string(s1, s2_already_lowered): @@ -43,7 +43,7 @@ class CHMReader(CHMFile): def __init__(self, input, log, input_encoding=None): CHMFile.__init__(self) - if isinstance(input, unicode_type): + if isinstance(input, str): enc = 'mbcs' if iswindows else filesystem_encoding try: input = input.encode(enc) @@ -192,7 +192,7 @@ def ExtractFiles(self, output_dir=os.getcwd(), debug_dump=False): with lopen(lpath, 'r+b') as f: data = f.read() data = self._reformat(data, lpath) - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') f.seek(0) f.truncate() diff --git a/src/calibre/ebooks/comic/input.py b/src/calibre/ebooks/comic/input.py index 2ea90bad94..62aea41a1e 100644 --- a/src/calibre/ebooks/comic/input.py +++ b/src/calibre/ebooks/comic/input.py @@ -16,7 +16,6 @@ from calibre.utils.icu import numeric_sort_key from calibre.utils.ipc.server import Server from calibre.utils.ipc.job import ParallelJob -from polyglot.builtins import unicode_type from polyglot.queue import Empty # If the specified screen has either dimension larger than this value, no image @@ -29,7 +28,7 @@ def extract_comic(path_to_comic_file): Un-archive the comic file. ''' tdir = PersistentTemporaryDirectory(suffix='_comic_extract') - if not isinstance(tdir, unicode_type): + if not isinstance(tdir, str): # Needed in case the zip file has wrongly encoded unicode file/dir # names tdir = tdir.decode(filesystem_encoding) diff --git a/src/calibre/ebooks/conversion/config.py b/src/calibre/ebooks/conversion/config.py index ec2da77273..b96c71ef3a 100644 --- a/src/calibre/ebooks/conversion/config.py +++ b/src/calibre/ebooks/conversion/config.py @@ -13,7 +13,6 @@ from calibre import sanitize_file_name from calibre.customize.conversion import OptionRecommendation from calibre.customize.ui import available_output_formats -from polyglot.builtins import unicode_type config_dir = os.path.join(config_dir, 'conversion') @@ -90,7 +89,7 @@ def __str__(self): def serialize(self): ans = json.dumps(self, indent=2, ensure_ascii=False) - if isinstance(ans, unicode_type): + if isinstance(ans, str): ans = ans.encode('utf-8') return b'json:' + ans diff --git a/src/calibre/ebooks/conversion/plugins/chm_input.py b/src/calibre/ebooks/conversion/plugins/chm_input.py index dab7b32a48..6653120cf5 100644 --- a/src/calibre/ebooks/conversion/plugins/chm_input.py +++ b/src/calibre/ebooks/conversion/plugins/chm_input.py @@ -10,7 +10,7 @@ from calibre.customize.conversion import InputFormatPlugin from calibre.ptempfile import TemporaryDirectory from calibre.constants import filesystem_encoding -from polyglot.builtins import unicode_type, as_bytes +from polyglot.builtins import as_bytes class CHMInput(InputFormatPlugin): @@ -37,7 +37,7 @@ def convert(self, stream, options, file_ext, log, accelerators): log.debug('Processing CHM...') with TemporaryDirectory('_chm2oeb') as tdir: - if not isinstance(tdir, unicode_type): + if not isinstance(tdir, str): tdir = tdir.decode(filesystem_encoding) html_input = plugin_for_input_format('html') for opt in html_input.options: @@ -128,7 +128,7 @@ def _create_html_root(self, hhcpath, log, encoding): base = os.path.dirname(os.path.abspath(htmlpath)) def unquote(x): - if isinstance(x, unicode_type): + if isinstance(x, str): x = x.encode('utf-8') return _unquote(x).decode('utf-8') diff --git a/src/calibre/ebooks/conversion/plugins/epub_output.py b/src/calibre/ebooks/conversion/plugins/epub_output.py index 10c7c513d7..e6cf2fdf04 100644 --- a/src/calibre/ebooks/conversion/plugins/epub_output.py +++ b/src/calibre/ebooks/conversion/plugins/epub_output.py @@ -12,7 +12,7 @@ OptionRecommendation) from calibre.ptempfile import TemporaryDirectory from calibre import CurrentDir -from polyglot.builtins import unicode_type, as_bytes +from polyglot.builtins import as_bytes block_level_tags = ( 'address', @@ -225,15 +225,15 @@ def convert(self, oeb, output_path, input_plugin, opts, log): identifiers = oeb.metadata['identifier'] uuid = None for x in identifiers: - if x.get(OPF('scheme'), None).lower() == 'uuid' or unicode_type(x).startswith('urn:uuid:'): - uuid = unicode_type(x).split(':')[-1] + if x.get(OPF('scheme'), None).lower() == 'uuid' or str(x).startswith('urn:uuid:'): + uuid = str(x).split(':')[-1] break encrypted_fonts = getattr(input_plugin, 'encrypted_fonts', []) if uuid is None: self.log.warn('No UUID identifier found') from uuid import uuid4 - uuid = unicode_type(uuid4()) + uuid = str(uuid4()) oeb.metadata.add('identifier', uuid, scheme='uuid', id=uuid) if encrypted_fonts and not uuid.startswith('urn:uuid:'): @@ -241,7 +241,7 @@ def convert(self, oeb, output_path, input_plugin, opts, log): # for some absurd reason, or it will throw a hissy fit and refuse # to use the obfuscated fonts. for x in identifiers: - if unicode_type(x) == uuid: + if str(x) == uuid: x.content = 'urn:uuid:'+uuid with TemporaryDirectory('_epub_output') as tdir: @@ -336,7 +336,7 @@ def encrypt_fonts(self, uris, tdir, uuid): # {{{ f.write(bytes(bytearray(data[i] ^ key[i%16] for i in range(1024)))) else: self.log.warn('Font', path, 'is invalid, ignoring') - if not isinstance(uri, unicode_type): + if not isinstance(uri, str): uri = uri.decode('utf-8') fonts.append(''' diff --git a/src/calibre/ebooks/conversion/plugins/html_input.py b/src/calibre/ebooks/conversion/plugins/html_input.py index e943c51655..3e74de67bb 100644 --- a/src/calibre/ebooks/conversion/plugins/html_input.py +++ b/src/calibre/ebooks/conversion/plugins/html_input.py @@ -17,7 +17,7 @@ from calibre.utils.filenames import ascii_filename from calibre.utils.imghdr import what from calibre.utils.localization import get_lang -from polyglot.builtins import as_unicode, unicode_type +from polyglot.builtins import as_unicode def sanitize_file_name(x): @@ -144,7 +144,7 @@ def create_oebbook(self, htmlpath, basedir, opts, log, mi): if not metadata.title: oeb.logger.warn('Title not specified') metadata.add('title', self.oeb.translate(__('Unknown'))) - bookid = unicode_type(uuid.uuid4()) + bookid = str(uuid.uuid4()) metadata.add('identifier', bookid, id='uuid_id', scheme='uuid') for ident in metadata.identifier: if 'id' in ident.attrib: @@ -233,7 +233,7 @@ def create_oebbook(self, htmlpath, basedir, opts, log, mi): def link_to_local_path(self, link_, base=None): from calibre.ebooks.html.input import Link - if not isinstance(link_, unicode_type): + if not isinstance(link_, str): try: link_ = link_.decode('utf-8', 'error') except: @@ -298,7 +298,7 @@ def resource_adder(self, link_, base=None): # bhref refers to an already existing file. The read() method of # DirContainer will call unquote on it before trying to read the # file, therefore we quote it here. - if isinstance(bhref, unicode_type): + if isinstance(bhref, str): bhref = bhref.encode('utf-8') item.html_input_href = as_unicode(quote(bhref)) if is_stylesheet: diff --git a/src/calibre/ebooks/conversion/plugins/html_output.py b/src/calibre/ebooks/conversion/plugins/html_output.py index 9323d3c65e..d35fabb5f8 100644 --- a/src/calibre/ebooks/conversion/plugins/html_output.py +++ b/src/calibre/ebooks/conversion/plugins/html_output.py @@ -10,7 +10,6 @@ from calibre.customize.conversion import OutputFormatPlugin, OptionRecommendation from calibre import CurrentDir from calibre.ptempfile import PersistentTemporaryDirectory -from polyglot.builtins import unicode_type def relpath(*args): @@ -140,7 +139,7 @@ def convert(self, oeb_book, output_path, input_plugin, opts, log): toc=html_toc, meta=meta, nextLink=nextLink, tocUrl=tocUrl, cssLink=cssLink, firstContentPageLink=nextLink) - if isinstance(t, unicode_type): + if isinstance(t, str): t = t.encode('utf-8') f.write(t) diff --git a/src/calibre/ebooks/conversion/plugins/htmlz_output.py b/src/calibre/ebooks/conversion/plugins/htmlz_output.py index 0f5d9b5333..2c07375ef1 100644 --- a/src/calibre/ebooks/conversion/plugins/htmlz_output.py +++ b/src/calibre/ebooks/conversion/plugins/htmlz_output.py @@ -11,7 +11,6 @@ from calibre.customize.conversion import OutputFormatPlugin, \ OptionRecommendation from calibre.ptempfile import TemporaryDirectory -from polyglot.builtins import unicode_type class HTMLZOutput(OutputFormatPlugin): @@ -80,9 +79,9 @@ def convert(self, oeb_book, output_path, input_plugin, opts, log): fname = u'index' if opts.htmlz_title_filename: from calibre.utils.filenames import shorten_components_to - fname = shorten_components_to(100, (ascii_filename(unicode_type(oeb_book.metadata.title[0])),))[0] + fname = shorten_components_to(100, (ascii_filename(str(oeb_book.metadata.title[0])),))[0] with open(os.path.join(tdir, fname+u'.html'), 'wb') as tf: - if isinstance(html, unicode_type): + if isinstance(html, str): html = html.encode('utf-8') tf.write(html) diff --git a/src/calibre/ebooks/conversion/plugins/lrf_output.py b/src/calibre/ebooks/conversion/plugins/lrf_output.py index 2a13288296..718db0a55a 100644 --- a/src/calibre/ebooks/conversion/plugins/lrf_output.py +++ b/src/calibre/ebooks/conversion/plugins/lrf_output.py @@ -10,7 +10,6 @@ from calibre.customize.conversion import OutputFormatPlugin from calibre.customize.conversion import OptionRecommendation -from polyglot.builtins import unicode_type class LRFOptions: @@ -18,7 +17,7 @@ class LRFOptions: def __init__(self, output, opts, oeb): def f2s(f): try: - return unicode_type(f[0]) + return str(f[0]) except: return '' m = oeb.metadata @@ -32,13 +31,13 @@ def f2s(f): self.title_sort = self.author_sort = '' for x in m.creator: if x.role == 'aut': - self.author = unicode_type(x) - fa = unicode_type(getattr(x, 'file_as', '')) + self.author = str(x) + fa = str(getattr(x, 'file_as', '')) if fa: self.author_sort = fa for x in m.title: - if unicode_type(x.file_as): - self.title_sort = unicode_type(x.file_as) + if str(x.file_as): + self.title_sort = str(x.file_as) self.freetext = f2s(m.description) self.category = f2s(m.subject) self.cover = None diff --git a/src/calibre/ebooks/conversion/plugins/mobi_input.py b/src/calibre/ebooks/conversion/plugins/mobi_input.py index 64d71c8a1a..7888f03e2d 100644 --- a/src/calibre/ebooks/conversion/plugins/mobi_input.py +++ b/src/calibre/ebooks/conversion/plugins/mobi_input.py @@ -7,7 +7,6 @@ import os from calibre.customize.conversion import InputFormatPlugin -from polyglot.builtins import unicode_type class MOBIInput(InputFormatPlugin): @@ -51,7 +50,7 @@ def convert(self, stream, options, file_ext, log, raw = parse_cache.pop('calibre_raw_mobi_markup', False) if raw: - if isinstance(raw, unicode_type): + if isinstance(raw, str): raw = raw.encode('utf-8') with lopen('debug-raw.html', 'wb') as f: f.write(raw) diff --git a/src/calibre/ebooks/conversion/plugins/mobi_output.py b/src/calibre/ebooks/conversion/plugins/mobi_output.py index e0501ca639..425b992fcd 100644 --- a/src/calibre/ebooks/conversion/plugins/mobi_output.py +++ b/src/calibre/ebooks/conversion/plugins/mobi_output.py @@ -8,7 +8,6 @@ from calibre.customize.conversion import (OutputFormatPlugin, OptionRecommendation) -from polyglot.builtins import unicode_type def remove_html_cover(oeb, log): @@ -122,7 +121,7 @@ def check_for_masthead(self): if not found: from calibre.ebooks import generate_masthead self.oeb.log.debug('No masthead found in manifest, generating default mastheadImage...') - raw = generate_masthead(unicode_type(self.oeb.metadata['title'][0])) + raw = generate_masthead(str(self.oeb.metadata['title'][0])) id, href = self.oeb.manifest.generate('masthead', 'masthead') self.oeb.manifest.add(id, href, 'image/gif', data=raw) self.oeb.guide.add('masthead', 'Masthead Image', href) @@ -166,7 +165,7 @@ def periodicalize_toc(self): sec.nodes.remove(a) root = TOC(klass='periodical', href=self.oeb.spine[0].href, - title=unicode_type(self.oeb.metadata.title[0])) + title=str(self.oeb.metadata.title[0])) for s in sections: if articles[id(s)]: diff --git a/src/calibre/ebooks/conversion/plugins/pdf_output.py b/src/calibre/ebooks/conversion/plugins/pdf_output.py index 66ff9d6060..f9fe1b96e5 100644 --- a/src/calibre/ebooks/conversion/plugins/pdf_output.py +++ b/src/calibre/ebooks/conversion/plugins/pdf_output.py @@ -14,7 +14,7 @@ from calibre.customize.conversion import (OutputFormatPlugin, OptionRecommendation) from calibre.ptempfile import TemporaryDirectory -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems UNITS = ('millimeter', 'centimeter', 'point', 'inch' , 'pica' , 'didot', 'cicero', 'devicepixel') @@ -193,8 +193,8 @@ def convert_images(self, images): def get_cover_data(self): oeb = self.oeb - if (oeb.metadata.cover and unicode_type(oeb.metadata.cover[0]) in oeb.manifest.ids): - cover_id = unicode_type(oeb.metadata.cover[0]) + if (oeb.metadata.cover and str(oeb.metadata.cover[0]) in oeb.manifest.ids): + cover_id = str(oeb.metadata.cover[0]) item = oeb.manifest.ids[cover_id] if isinstance(item.data, bytes): self.cover_data = item.data diff --git a/src/calibre/ebooks/conversion/plugins/pml_output.py b/src/calibre/ebooks/conversion/plugins/pml_output.py index 4daf944d75..5d8619af8a 100644 --- a/src/calibre/ebooks/conversion/plugins/pml_output.py +++ b/src/calibre/ebooks/conversion/plugins/pml_output.py @@ -10,7 +10,6 @@ from calibre.customize.conversion import (OutputFormatPlugin, OptionRecommendation) from calibre.ptempfile import TemporaryDirectory -from polyglot.builtins import unicode_type class PMLOutput(OutputFormatPlugin): @@ -42,7 +41,7 @@ def convert(self, oeb_book, output_path, input_plugin, opts, log): with TemporaryDirectory('_pmlz_output') as tdir: pmlmlizer = PMLMLizer(log) - pml = unicode_type(pmlmlizer.extract_content(oeb_book, opts)) + pml = str(pmlmlizer.extract_content(oeb_book, opts)) with lopen(os.path.join(tdir, 'index.pml'), 'wb') as out: out.write(pml.encode(opts.pml_output_encoding, 'replace')) diff --git a/src/calibre/ebooks/conversion/plugins/recipe_input.py b/src/calibre/ebooks/conversion/plugins/recipe_input.py index 43cca8b130..104a842c08 100644 --- a/src/calibre/ebooks/conversion/plugins/recipe_input.py +++ b/src/calibre/ebooks/conversion/plugins/recipe_input.py @@ -11,7 +11,6 @@ from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation from calibre.constants import numeric_version from calibre import walk -from polyglot.builtins import unicode_type class RecipeDisabled(Exception): @@ -164,6 +163,6 @@ def specialize(self, oeb, opts, log, output_fmt): def save_download(self, zf): raw = self.recipe_source - if isinstance(raw, unicode_type): + if isinstance(raw, str): raw = raw.encode('utf-8') zf.writestr('download.recipe', raw) diff --git a/src/calibre/ebooks/conversion/plugins/snb_input.py b/src/calibre/ebooks/conversion/plugins/snb_input.py index a349862c1d..66ede4cea5 100644 --- a/src/calibre/ebooks/conversion/plugins/snb_input.py +++ b/src/calibre/ebooks/conversion/plugins/snb_input.py @@ -10,7 +10,6 @@ from calibre.customize.conversion import InputFormatPlugin from calibre.ptempfile import TemporaryDirectory from calibre.utils.filenames import ascii_filename -from polyglot.builtins import unicode_type HTML_TEMPLATE = '%s\n%s\n' @@ -75,7 +74,7 @@ def convert(self, stream, options, file_ext, log, if d['cover'] != '': oeb.guide.add('cover', 'Cover', d['cover']) - bookid = unicode_type(uuid.uuid4()) + bookid = str(uuid.uuid4()) oeb.metadata.add('identifier', bookid, id='uuid_id', scheme='uuid') for ident in oeb.metadata.identifier: if 'id' in ident.attrib: diff --git a/src/calibre/ebooks/conversion/plugins/snb_output.py b/src/calibre/ebooks/conversion/plugins/snb_output.py index e8a75d96e8..0c89fd10f3 100644 --- a/src/calibre/ebooks/conversion/plugins/snb_output.py +++ b/src/calibre/ebooks/conversion/plugins/snb_output.py @@ -10,7 +10,6 @@ from calibre.customize.conversion import OutputFormatPlugin, OptionRecommendation from calibre.ptempfile import TemporaryDirectory from calibre.constants import __appname__, __version__ -from polyglot.builtins import unicode_type class SNBOutput(OutputFormatPlugin): @@ -75,20 +74,20 @@ def convert(self, oeb_book, output_path, input_plugin, opts, log): # Process Meta data meta = oeb_book.metadata if meta.title: - title = unicode_type(meta.title[0]) + title = str(meta.title[0]) else: title = '' - authors = [unicode_type(x) for x in meta.creator if x.role == 'aut'] + authors = [str(x) for x in meta.creator if x.role == 'aut'] if meta.publisher: - publishers = unicode_type(meta.publisher[0]) + publishers = str(meta.publisher[0]) else: publishers = '' if meta.language: - lang = unicode_type(meta.language[0]).upper() + lang = str(meta.language[0]).upper() else: lang = '' if meta.description: - abstract = unicode_type(meta.description[0]) + abstract = str(meta.description[0]) else: abstract = '' diff --git a/src/calibre/ebooks/conversion/plumber.py b/src/calibre/ebooks/conversion/plumber.py index 037bc1ad46..8de61ce6a6 100644 --- a/src/calibre/ebooks/conversion/plumber.py +++ b/src/calibre/ebooks/conversion/plumber.py @@ -20,7 +20,7 @@ from calibre import (extract, walk, isbytestring, filesystem_encoding, get_types_map) from calibre.constants import __version__ -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes DEBUG_README=b''' This debug folder contains snapshots of the e-book as it passes through the @@ -794,7 +794,7 @@ def __init__(self, input, output, log, report_progress=DummyReporter(), def unarchive(self, path, tdir): extract(path, tdir) files = list(walk(tdir)) - files = [f if isinstance(f, unicode_type) else f.decode(filesystem_encoding) + files = [f if isinstance(f, str) else f.decode(filesystem_encoding) for f in files] from calibre.customize.ui import available_input_formats fmts = set(available_input_formats()) @@ -847,7 +847,7 @@ def get_option_help(self, name): rec = self.get_option_by_name(name) help = getattr(rec, 'help', None) if help is not None: - return help.replace('%default', unicode_type(rec.recommended_value)) + return help.replace('%default', str(rec.recommended_value)) def get_all_help(self): ans = {} @@ -915,7 +915,7 @@ def opts_to_mi(self, mi): try: val = parse_date(val, assume_utc=x=='timestamp') except: - self.log.exception(_('Failed to parse date/time') + ' ' + unicode_type(val)) + self.log.exception(_('Failed to parse date/time') + ' ' + str(val)) continue setattr(mi, x, val) diff --git a/src/calibre/ebooks/conversion/preprocess.py b/src/calibre/ebooks/conversion/preprocess.py index 4cf6b861aa..dd1322c8a0 100644 --- a/src/calibre/ebooks/conversion/preprocess.py +++ b/src/calibre/ebooks/conversion/preprocess.py @@ -10,7 +10,6 @@ from math import ceil from calibre import entity_to_unicode, as_unicode -from polyglot.builtins import unicode_type XMLDECL_RE = re.compile(r'^\s*<[?]xml.*?[?]>') SVG_NS = 'http://www.w3.org/2000/svg' @@ -75,8 +74,8 @@ def smarten_punctuation(html, log=None): from calibre.ebooks.conversion.utils import HeuristicProcessor preprocessor = HeuristicProcessor(log=log) from uuid import uuid4 - start = 'calibre-smartypants-'+unicode_type(uuid4()) - stop = 'calibre-smartypants-'+unicode_type(uuid4()) + start = 'calibre-smartypants-'+str(uuid4()) + stop = 'calibre-smartypants-'+str(uuid4()) html = html.replace('', stop) html = preprocessor.fix_nbsp_indents(html) @@ -152,20 +151,20 @@ def line_histogram(self, percent): maxLineLength=1900 # Discard larger than this to stay in range buckets=20 # Each line is divided into a bucket based on length - # print("there are "+unicode_type(len(lines))+" lines") + # print("there are "+str(len(lines))+" lines") # max = 0 # for line in self.lines: # l = len(line) # if l > max: # max = l - # print("max line found is "+unicode_type(max)) + # print("max line found is "+str(max)) # Build the line length histogram hRaw = [0 for i in range(0,buckets)] for line in self.lines: l = len(line) if l > minLineLength and l < maxLineLength: l = int(l // 100) - # print("adding "+unicode_type(l)) + # print("adding "+str(l)) hRaw[l]+=1 # Normalize the histogram into percents @@ -174,8 +173,8 @@ def line_histogram(self, percent): h = [float(count)/totalLines for count in hRaw] else: h = [] - # print("\nhRaw histogram lengths are: "+unicode_type(hRaw)) - # print(" percents are: "+unicode_type(h)+"\n") + # print("\nhRaw histogram lengths are: "+str(hRaw)) + # print(" percents are: "+str(h)+"\n") # Find the biggest bucket maxValue = 0 @@ -187,7 +186,7 @@ def line_histogram(self, percent): # print("Line lengths are too variable. Not unwrapping.") return False else: - # print(unicode_type(maxValue)+" of the lines were in one bucket") + # print(str(maxValue)+" of the lines were in one bucket") return True @@ -223,8 +222,8 @@ def dehyphenate(self, match): wraptags = match.group('wraptags') except: wraptags = '' - hyphenated = unicode_type(firsthalf) + "-" + unicode_type(secondhalf) - dehyphenated = unicode_type(firsthalf) + unicode_type(secondhalf) + hyphenated = str(firsthalf) + "-" + str(secondhalf) + dehyphenated = str(firsthalf) + str(secondhalf) if self.suffixes.match(secondhalf) is None: lookupword = self.removesuffixes.sub('', dehyphenated) else: @@ -330,7 +329,7 @@ def __call__(self, data, add_namespace=False): # are commented lines before the first @import or @charset rule. Since # the conversion will remove all stylesheets anyway, we don't lose # anything - data = re.sub(unicode_type(r'/\*.*?\*/'), '', data, flags=re.DOTALL) + data = re.sub(r'/\*.*?\*/', '', data, flags=re.DOTALL) ans, namespaced = [], False for line in data.splitlines(): @@ -538,7 +537,7 @@ def do_search_replace(search_pattern, replace_txt): docanalysis = DocAnalysis('pdf', html) length = docanalysis.line_length(getattr(self.extra_opts, 'unwrap_factor')) if length: - # print("The pdf line length returned is " + unicode_type(length)) + # print("The pdf line length returned is " + str(length)) # unwrap em/en dashes end_rules.append((re.compile( r'(?<=.{%i}[–—])\s*

\s*(?=[\[a-z\d])' % length), lambda match: '')) diff --git a/src/calibre/ebooks/conversion/utils.py b/src/calibre/ebooks/conversion/utils.py index fb49bde3f4..2ec154a951 100644 --- a/src/calibre/ebooks/conversion/utils.py +++ b/src/calibre/ebooks/conversion/utils.py @@ -11,7 +11,6 @@ from calibre.ebooks.conversion.preprocess import DocAnalysis, Dehyphenator from calibre.utils.logging import default_log from calibre.utils.wordcount import get_wordcount_obj -from polyglot.builtins import unicode_type class HeuristicProcessor: @@ -54,8 +53,8 @@ def chapter_head(self, match): title = match.group('title') if not title: self.html_preprocess_sections = self.html_preprocess_sections + 1 - self.log.debug("marked " + unicode_type(self.html_preprocess_sections) + - " chapters. - " + unicode_type(chap)) + self.log.debug("marked " + str(self.html_preprocess_sections) + + " chapters. - " + str(chap)) return '

'+chap+'

\n' else: delete_whitespace = re.compile('^\\s*(?P.*?)\\s*$') @@ -63,16 +62,16 @@ def chapter_head(self, match): txt_chap = delete_quotes.sub('', delete_whitespace.sub('\\g', html2text(chap))) txt_title = delete_quotes.sub('', delete_whitespace.sub('\\g', html2text(title))) self.html_preprocess_sections = self.html_preprocess_sections + 1 - self.log.debug("marked " + unicode_type(self.html_preprocess_sections) + - " chapters & titles. - " + unicode_type(chap) + ", " + unicode_type(title)) + self.log.debug("marked " + str(self.html_preprocess_sections) + + " chapters & titles. - " + str(chap) + ", " + str(title)) return '

'+chap+'

\n

'+title+'

\n' def chapter_break(self, match): chap = match.group('section') styles = match.group('styles') self.html_preprocess_sections = self.html_preprocess_sections + 1 - self.log.debug("marked " + unicode_type(self.html_preprocess_sections) + - " section markers based on punctuation. - " + unicode_type(chap)) + self.log.debug("marked " + str(self.html_preprocess_sections) + + " section markers based on punctuation. - " + str(chap)) return '<'+styles+' style="page-break-before:always">'+chap def analyze_title_matches(self, match): @@ -115,8 +114,8 @@ def no_markup(self, raw, percent): line_end = line_end_ere.findall(raw) tot_htm_ends = len(htm_end) tot_ln_fds = len(line_end) - # self.log.debug("There are " + unicode_type(tot_ln_fds) + " total Line feeds, and " + - # unicode_type(tot_htm_ends) + " marked up endings") + # self.log.debug("There are " + str(tot_ln_fds) + " total Line feeds, and " + + # str(tot_htm_ends) + " marked up endings") if percent > 1: percent = 1 @@ -124,7 +123,7 @@ def no_markup(self, raw, percent): percent = 0 min_lns = tot_ln_fds * percent - # self.log.debug("There must be fewer than " + unicode_type(min_lns) + " unmarked lines to add markup") + # self.log.debug("There must be fewer than " + str(min_lns) + " unmarked lines to add markup") return min_lns > tot_htm_ends def dump(self, raw, where): @@ -161,17 +160,17 @@ def markup_italicis(self, html): ] ITALICIZE_STYLE_PATS = [ - unicode_type(r'(?msu)(?<=[\s>"“\'‘])_\*/(?P[^\*_]+)/\*_'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])~~(?P[^~]+)~~'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])_/(?P[^/_]+)/_'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])_\*(?P[^\*_]+)\*_'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])\*/(?P[^/\*]+)/\*'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])/:(?P[^:/]+):/'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])\|:(?P[^:\|]+):\|'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])\*(?P[^\*]+)\*'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])~(?P[^~]+)~'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])/(?P[^/\*><]+)/'), - unicode_type(r'(?msu)(?<=[\s>"“\'‘])_(?P[^_]+)_'), + r'(?msu)(?<=[\s>"“\'‘])_\*/(?P[^\*_]+)/\*_', + r'(?msu)(?<=[\s>"“\'‘])~~(?P[^~]+)~~', + r'(?msu)(?<=[\s>"“\'‘])_/(?P[^/_]+)/_', + r'(?msu)(?<=[\s>"“\'‘])_\*(?P[^\*_]+)\*_', + r'(?msu)(?<=[\s>"“\'‘])\*/(?P[^/\*]+)/\*', + r'(?msu)(?<=[\s>"“\'‘])/:(?P[^:/]+):/', + r'(?msu)(?<=[\s>"“\'‘])\|:(?P[^:\|]+):\|', + r'(?msu)(?<=[\s>"“\'‘])\*(?P[^\*]+)\*', + r'(?msu)(?<=[\s>"“\'‘])~(?P[^~]+)~', + r'(?msu)(?<=[\s>"“\'‘])/(?P[^/\*><]+)/', + r'(?msu)(?<=[\s>"“\'‘])_(?P[^_]+)_', ] for word in ITALICIZE_WORDS: @@ -181,10 +180,10 @@ def markup_italicis(self, html): search_text = re.sub(r'<[^>]*>', '', search_text) for pat in ITALICIZE_STYLE_PATS: for match in re.finditer(pat, search_text): - ital_string = unicode_type(match.group('words')) - # self.log.debug("italicising "+unicode_type(match.group(0))+" with "+ital_string+"") + ital_string = str(match.group('words')) + # self.log.debug("italicising "+str(match.group(0))+" with "+ital_string+"") try: - html = re.sub(re.escape(unicode_type(match.group(0))), '%s' % ital_string, html) + html = re.sub(re.escape(str(match.group(0))), '%s' % ital_string, html) except OverflowError: # match.group(0) was too large to be compiled into a regex continue @@ -209,10 +208,10 @@ def markup_chapters(self, html, wordcount, blanks_between_paragraphs): if wordcount > 200000: typical_chapters = 15000. self.min_chapters = int(ceil(wordcount / typical_chapters)) - self.log.debug("minimum chapters required are: "+unicode_type(self.min_chapters)) + self.log.debug("minimum chapters required are: "+str(self.min_chapters)) heading = re.compile(']*>', re.IGNORECASE) self.html_preprocess_sections = len(heading.findall(html)) - self.log.debug("found " + unicode_type(self.html_preprocess_sections) + " pre-existing headings") + self.log.debug("found " + str(self.html_preprocess_sections) + " pre-existing headings") # Build the Regular Expressions in pieces init_lookahead = "(?=<(p|div))" @@ -302,7 +301,7 @@ def recurse_patterns(html, analyze): if n_lookahead_req: n_lookahead = re.sub("(ou|in|cha)", "lookahead_", full_chapter_line) if not analyze: - self.log.debug("Marked " + unicode_type(self.html_preprocess_sections) + " headings, " + log_message) + self.log.debug("Marked " + str(self.html_preprocess_sections) + " headings, " + log_message) chapter_marker = arg_ignorecase+init_lookahead+full_chapter_line+blank_lines+lp_n_lookahead_open+n_lookahead+lp_n_lookahead_close+ \ lp_opt_title_open+title_line_open+title_header_open+lp_title+title_header_close+title_line_close+lp_opt_title_close @@ -316,10 +315,10 @@ def recurse_patterns(html, analyze): 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, "+ - unicode_type(self.chapters_with_title)+" chapters with titles, "+ - unicode_type(float(self.chapters_with_title) / float(hits))+" percent. ") + str(type_name)+" had "+str(hits)+ + " hits - "+str(self.chapters_no_title)+" chapters with no title, "+ + str(self.chapters_with_title)+" chapters with titles, "+ + str(float(self.chapters_with_title) / float(hits))+" percent. ") if type_name == 'common': analysis_result.append([chapter_type, n_lookahead_req, strict_title, ignorecase, title_req, log_message, type_name]) elif self.min_chapters <= hits < max_chapters or self.min_chapters < 3 > hits: @@ -336,8 +335,8 @@ def recurse_patterns(html, analyze): words_per_chptr = wordcount if words_per_chptr > 0 and self.html_preprocess_sections > 0: words_per_chptr = wordcount // self.html_preprocess_sections - self.log.debug("Total wordcount is: "+ unicode_type(wordcount)+", Average words per section is: "+ - unicode_type(words_per_chptr)+", Marked up "+unicode_type(self.html_preprocess_sections)+" chapters") + self.log.debug("Total wordcount is: "+ str(wordcount)+", Average words per section is: "+ + str(words_per_chptr)+", Marked up "+str(self.html_preprocess_sections)+" chapters") return html def punctuation_unwrap(self, length, content, format): @@ -367,8 +366,8 @@ def style_unwrap(match): # define the pieces of the regex # (?)?\\s*()?" blanklines = "\\s*(?P<(p|span|div)[^>]*>\\s*(<(p|span|div)[^>]*>\\s*\\s*)\\s*){0,3}\\s*" @@ -428,18 +427,18 @@ def arrange_htm_line_endings(self, html): return html def fix_nbsp_indents(self, html): - txtindent = re.compile(unicode_type(r'<(?Pp|div)(?P[^>]*)>\s*(?P(]*>\s*)+)?\s*(\u00a0){2,}'), re.IGNORECASE) + txtindent = re.compile(r'<(?Pp|div)(?P[^>]*)>\s*(?P(]*>\s*)+)?\s*(\u00a0){2,}', re.IGNORECASE) html = txtindent.sub(self.insert_indent, html) if self.found_indents > 1: - self.log.debug("replaced "+unicode_type(self.found_indents)+ " nbsp indents with inline styles") + self.log.debug("replaced "+str(self.found_indents)+ " nbsp indents with inline styles") return html def cleanup_markup(self, html): # remove remaining non-breaking spaces - html = re.sub(unicode_type(r'\u00a0'), ' ', html) + html = re.sub(r'\u00a0', ' ', html) # Get rid of various common microsoft specific tags which can cause issues later # Get rid of empty tags to simplify other processing - html = re.sub(unicode_type(r'\s*\s*'), ' ', html) + html = re.sub(r'\s*\s*', ' ', html) # Delete microsoft 'smart' tags html = re.sub('(?i)', '', html) # Re-open self closing paragraph tags @@ -479,8 +478,8 @@ def analyze_blanks(self, html): blanklines = self.blankreg.findall(html) lines = self.linereg.findall(html) if len(lines) > 1: - self.log.debug("There are " + unicode_type(len(blanklines)) + " blank lines. " + - unicode_type(float(len(blanklines)) / float(len(lines))) + " percent blank") + self.log.debug("There are " + str(len(blanklines)) + " blank lines. " + + str(float(len(blanklines)) / float(len(lines))) + " percent blank") if float(len(blanklines)) / float(len(lines)) > 0.40: return True @@ -502,11 +501,11 @@ def merge_matches(match): lines = float(len(self.single_blank.findall(to_merge))) - 1. em = base_em + (em_per_line * lines) if to_merge.find('whitespace'): - newline = self.any_multi_blank.sub('\n

', match.group(0)) + newline = self.any_multi_blank.sub('\n

', match.group(0)) else: - newline = self.any_multi_blank.sub('\n

', match.group(0)) + newline = self.any_multi_blank.sub('\n

', match.group(0)) return newline html = self.any_multi_blank.sub(merge_matches, html) @@ -530,9 +529,9 @@ def merge_header_whitespace(match): top_margin = '' bottom_margin = '' if initblanks is not None: - top_margin = 'margin-top:'+unicode_type(len(self.single_blank.findall(initblanks)))+'em;' + top_margin = 'margin-top:'+str(len(self.single_blank.findall(initblanks)))+'em;' if endblanks is not None: - bottom_margin = 'margin-bottom:'+unicode_type(len(self.single_blank.findall(endblanks)))+'em;' + bottom_margin = 'margin-bottom:'+str(len(self.single_blank.findall(endblanks)))+'em;' if initblanks is None and endblanks is None: return content @@ -609,7 +608,7 @@ def markup_user_break(self, replacement_break): else: replacement_break = re.sub('(?i)(width=\\d+\\%?|width:\\s*\\d+(\\%|px|pt|em)?;?)', '', replacement_break) divpercent = (100 - width) // 2 - hr_open = re.sub('45', unicode_type(divpercent), hr_open) + hr_open = re.sub('45', str(divpercent), hr_open) scene_break = hr_open+replacement_break+'' else: scene_break = hr_open+'
' @@ -669,12 +668,12 @@ def convert_styles(match): else: styles = match.group('styles').split(';') is_paragraph = self.check_paragraph(content) - # print "styles for this line are: "+unicode_type(styles) + # print "styles for this line are: "+str(styles) split_styles = [] for style in styles: - # print "style is: "+unicode_type(style) + # print "style is: "+str(style) newstyle = style.split(':') - # print "newstyle is: "+unicode_type(newstyle) + # print "newstyle is: "+str(newstyle) split_styles.append(newstyle) styles = split_styles for style, setting in styles: @@ -685,7 +684,7 @@ def convert_styles(match): if 9 < setting < 14: text_indent = indented_text else: - text_indent = style+':'+unicode_type(setting)+'pt;' + text_indent = style+':'+str(setting)+'pt;' if style == 'padding': setting = re.sub('pt', '', setting).split(' ') if int(setting[1]) < 16 and int(setting[3]) < 16: @@ -706,23 +705,23 @@ def convert_styles(match): blockquote_open_loop = blockquote_open if debugabby: self.log.debug('\n\n******\n') - self.log.debug('padding top is: '+unicode_type(setting[0])) - self.log.debug('padding right is:' +unicode_type(setting[1])) - self.log.debug('padding bottom is: ' + unicode_type(setting[2])) - self.log.debug('padding left is: ' +unicode_type(setting[3])) + self.log.debug('padding top is: '+str(setting[0])) + self.log.debug('padding right is:' +str(setting[1])) + self.log.debug('padding bottom is: ' + str(setting[2])) + self.log.debug('padding left is: ' +str(setting[3])) - # print "text-align is: "+unicode_type(text_align) - # print "\n***\nline is:\n "+unicode_type(match.group(0))+'\n' + # print "text-align is: "+str(text_align) + # print "\n***\nline is:\n "+str(match.group(0))+'\n' if debugabby: - # print "this line is a paragraph = "+unicode_type(is_paragraph)+", previous line was "+unicode_type(self.previous_was_paragraph) + # print "this line is a paragraph = "+str(is_paragraph)+", previous line was "+str(self.previous_was_paragraph) self.log.debug("styles for this line were:", styles) self.log.debug('newline is:') self.log.debug(blockquote_open_loop+blockquote_close_loop+ paragraph_before+'

'+content+'

'+paragraph_after+'\n\n\n\n\n') - # print "is_paragraph is "+unicode_type(is_paragraph)+", previous_was_paragraph is "+unicode_type(self.previous_was_paragraph) + # print "is_paragraph is "+str(is_paragraph)+", previous_was_paragraph is "+str(self.previous_was_paragraph) self.previous_was_paragraph = is_paragraph - # print "previous_was_paragraph is now set to "+unicode_type(self.previous_was_paragraph)+"\n\n\n" + # print "previous_was_paragraph is now set to "+str(self.previous_was_paragraph)+"\n\n\n" return blockquote_open_loop+blockquote_close_loop+paragraph_before+'

'+content+'

'+paragraph_after html = abbyy_line.sub(convert_styles, html) @@ -805,12 +804,12 @@ def __call__(self, html): # more of the lines break in the same region of the document then unwrapping is required docanalysis = DocAnalysis(format, html) hardbreaks = docanalysis.line_histogram(.50) - self.log.debug("Hard line breaks check returned "+unicode_type(hardbreaks)) + self.log.debug("Hard line breaks check returned "+str(hardbreaks)) # Calculate Length unwrap_factor = getattr(self.extra_opts, 'html_unwrap_factor', 0.4) length = docanalysis.line_length(unwrap_factor) - self.log.debug("Median line length is " + unicode_type(length) + ", calculated with " + format + " format") + self.log.debug("Median line length is " + str(length) + ", calculated with " + format + " format") # ##### Unwrap lines ###### if getattr(self.extra_opts, 'unwrap_lines', False): @@ -832,7 +831,7 @@ def __call__(self, html): # If still no sections after unwrapping mark split points on lines with no punctuation if self.html_preprocess_sections < self.min_chapters and getattr(self.extra_opts, 'markup_chapter_headings', False): self.log.debug("Looking for more split points based on punctuation," - " currently have " + unicode_type(self.html_preprocess_sections)) + " currently have " + str(self.html_preprocess_sections)) chapdetect3 = re.compile( r'<(?P(p|div)[^>]*)>\s*(?P
(]*>)?\s*(?!([\W]+\s*)+)' r'(<[ibu][^>]*>){0,2}\s*(]*>)?\s*(<[ibu][^>]*>){0,2}\s*(]*>)?\s*' diff --git a/src/calibre/ebooks/css_transform_rules.py b/src/calibre/ebooks/css_transform_rules.py index 09fe12df77..8efb390bd7 100644 --- a/src/calibre/ebooks/css_transform_rules.py +++ b/src/calibre/ebooks/css_transform_rules.py @@ -12,7 +12,7 @@ from calibre import force_unicode from calibre.ebooks import parse_css_length from calibre.ebooks.oeb.normalize_css import normalizers, safe_parser -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def compile_pat(pat): @@ -161,7 +161,7 @@ def transform_number(val, op, raw): v = op(v, val) if int(v) == v: v = int(v) - return unicode_type(v) + u + return str(v) + u class Rule: @@ -379,7 +379,7 @@ def apply_rule(style, **rule): r = Rule(**rule) decl = StyleDeclaration(safe_parser().parseStyle(style)) r.process_declaration(decl) - return unicode_type(decl) + return str(decl) class TestTransforms(unittest.TestCase): longMessage = True diff --git a/src/calibre/ebooks/docx/footnotes.py b/src/calibre/ebooks/docx/footnotes.py index b5eaecd4b3..36c1fea5f9 100644 --- a/src/calibre/ebooks/docx/footnotes.py +++ b/src/calibre/ebooks/docx/footnotes.py @@ -6,7 +6,7 @@ __copyright__ = '2013, Kovid Goyal ' from collections import OrderedDict -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class Note: @@ -52,8 +52,8 @@ def get_ref(self, ref): if note is not None and note.type == 'normal': self.counter += 1 anchor = 'note_%d' % self.counter - self.notes[anchor] = (unicode_type(self.counter), note) - return anchor, unicode_type(self.counter) + self.notes[anchor] = (str(self.counter), note) + return anchor, str(self.counter) return None, None def __iter__(self): diff --git a/src/calibre/ebooks/docx/numbering.py b/src/calibre/ebooks/docx/numbering.py index 16a1af875c..f5f193544f 100644 --- a/src/calibre/ebooks/docx/numbering.py +++ b/src/calibre/ebooks/docx/numbering.py @@ -14,7 +14,7 @@ from calibre.ebooks.docx.block_styles import ParagraphStyle from calibre.ebooks.docx.char_styles import RunStyle, inherit from calibre.ebooks.metadata import roman -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems STYLE_MAP = { 'aiueo': 'hiragana', @@ -291,7 +291,7 @@ def apply_markup(self, items, body, styles, object_map, images): seen_instances.add(num_id) p.tag = 'li' p.set('value', '%s' % counter[ilvl]) - p.set('list-lvl', unicode_type(ilvl)) + p.set('list-lvl', str(ilvl)) p.set('list-id', num_id) if lvl.num_template is not None: val = lvl.format_template(counter, ilvl, lvl.num_template) diff --git a/src/calibre/ebooks/docx/tables.py b/src/calibre/ebooks/docx/tables.py index b66eb051c1..bb1d8ebbdb 100644 --- a/src/calibre/ebooks/docx/tables.py +++ b/src/calibre/ebooks/docx/tables.py @@ -9,7 +9,7 @@ from calibre.ebooks.docx.block_styles import inherit, read_shd as rs, read_border, binary_property, border_props, ParagraphStyle, border_to_css from calibre.ebooks.docx.char_styles import RunStyle -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues # Read from XML {{{ read_shd = rs @@ -646,9 +646,9 @@ def apply_markup(self, rmap, page, parent=None): td = TD() style_map[td] = s = self.style_map[tc] if s.col_span is not inherit: - td.set('colspan', unicode_type(s.col_span)) + td.set('colspan', str(s.col_span)) if s.row_span is not inherit: - td.set('rowspan', unicode_type(s.row_span)) + td.set('rowspan', str(s.row_span)) td.tail = '\n\t\t\t' tr.append(td) for x in self.namespace.XPath('./w:p|./w:tbl')(tc): diff --git a/src/calibre/ebooks/docx/to_html.py b/src/calibre/ebooks/docx/to_html.py index 42cf5f3b42..72b4fd54fc 100644 --- a/src/calibre/ebooks/docx/to_html.py +++ b/src/calibre/ebooks/docx/to_html.py @@ -28,7 +28,7 @@ from calibre.ebooks.docx.settings import Settings from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.utils.localization import canonicalize_lang, lang_as_iso639_1 -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues NBSP = '\xa0' @@ -480,7 +480,7 @@ def p_parent(x): current_hyperlink = x elif x.tag.endswith('}instrText') and x.text and x.text.strip().startswith('TOC '): old_anchor = current_anchor - anchor = unicode_type(uuid.uuid4()) + anchor = str(uuid.uuid4()) self.anchor_map[anchor] = current_anchor = generate_anchor('toc', frozenset(itervalues(self.anchor_map))) self.toc_anchor = current_anchor if old_anchor is not None: @@ -507,7 +507,7 @@ def p_parent(x): if m is not None: n = min(6, max(1, int(m.group(1)))) dest.tag = 'h%d' % n - dest.set('data-heading-level', unicode_type(n)) + dest.set('data-heading-level', str(n)) if style.bidi is True: dest.set('dir', 'rtl') diff --git a/src/calibre/ebooks/docx/writer/container.py b/src/calibre/ebooks/docx/writer/container.py index 1c9071a1db..fcdb9a8a34 100644 --- a/src/calibre/ebooks/docx/writer/container.py +++ b/src/calibre/ebooks/docx/writer/container.py @@ -18,7 +18,7 @@ from calibre.utils.date import utcnow from calibre.utils.localization import canonicalize_lang, lang_as_iso639_1 from calibre.utils.zipfile import ZipFile -from polyglot.builtins import iteritems, unicode_type, native_string_type +from polyglot.builtins import iteritems, native_string_type def xml2str(root, pretty_print=False, with_tail=False): @@ -65,9 +65,9 @@ def w(x): def margin(which): val = page_margin(opts, which) - return w(which), unicode_type(int(val * 20)) + return w(which), str(int(val * 20)) body.append(E.sectPr( - E.pgSz(**{w('w'):unicode_type(width), w('h'):unicode_type(height)}), + E.pgSz(**{w('w'):str(width), w('h'):str(height)}), E.pgMar(**dict(map(margin, 'left top right bottom'.split()))), E.cols(**{w('space'):'720'}), E.docGrid(**{w('linePitch'):"360"}), diff --git a/src/calibre/ebooks/docx/writer/from_html.py b/src/calibre/ebooks/docx/writer/from_html.py index 985ae8ede8..eb11eb444a 100644 --- a/src/calibre/ebooks/docx/writer/from_html.py +++ b/src/calibre/ebooks/docx/writer/from_html.py @@ -18,7 +18,7 @@ from calibre.ebooks.oeb.stylizer import Stylizer as Sz, Style as St from calibre.ebooks.oeb.base import XPath, barename from calibre.utils.localization import lang_as_iso639_1 -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes def lang_for_tag(tag): @@ -108,7 +108,7 @@ def add_text(text, preserve_whitespace): for text, preserve_whitespace, bookmark in self.texts: if bookmark is not None: bid = links_manager.bookmark_id - makeelement(r, 'w:bookmarkStart', w_id=unicode_type(bid), w_name=bookmark) + makeelement(r, 'w:bookmarkStart', w_id=str(bid), w_name=bookmark) if text is None: makeelement(r, 'w:br', w_clear=preserve_whitespace) elif hasattr(text, 'xpath'): @@ -123,7 +123,7 @@ def add_text(text, preserve_whitespace): else: add_text('', preserve_whitespace) if bookmark is not None: - makeelement(r, 'w:bookmarkEnd', w_id=unicode_type(bid)) + makeelement(r, 'w:bookmarkEnd', w_id=str(bid)) def __repr__(self): return repr(self.texts) @@ -139,7 +139,7 @@ def is_empty(self): def style_weight(self): ans = 0 for text, preserve_whitespace, bookmark in self.texts: - if isinstance(text, unicode_type): + if isinstance(text, str): ans += len(text) return ans @@ -219,7 +219,7 @@ def serialize(self, body): p = makeelement(body, 'w:p') end_bookmarks = [] for bmark in self.bookmarks: - end_bookmarks.append(unicode_type(self.links_manager.bookmark_id)) + end_bookmarks.append(str(self.links_manager.bookmark_id)) makeelement(p, 'w:bookmarkStart', w_id=end_bookmarks[-1], w_name=bmark) if self.block_lang: rpr = makeelement(p, 'w:rPr') @@ -232,8 +232,8 @@ def serialize(self, body): self.float_spec.serialize(self, ppr) if self.numbering_id is not None: numpr = makeelement(ppr, 'w:numPr') - makeelement(numpr, 'w:ilvl', w_val=unicode_type(self.numbering_id[1])) - makeelement(numpr, 'w:numId', w_val=unicode_type(self.numbering_id[0])) + makeelement(numpr, 'w:ilvl', w_val=str(self.numbering_id[1])) + makeelement(numpr, 'w:numId', w_val=str(self.numbering_id[0])) if self.linked_style is not None: makeelement(ppr, 'w:pStyle', w_val=self.linked_style.id) elif self.style.id: @@ -453,8 +453,8 @@ def __call__(self): if self.add_toc: self.links_manager.process_toc_links(self.oeb) - if self.add_cover and self.oeb.metadata.cover and unicode_type(self.oeb.metadata.cover[0]) in self.oeb.manifest.ids: - cover_id = unicode_type(self.oeb.metadata.cover[0]) + if self.add_cover and self.oeb.metadata.cover and str(self.oeb.metadata.cover[0]) in self.oeb.manifest.ids: + cover_id = str(self.oeb.metadata.cover[0]) item = self.oeb.manifest.ids[cover_id] self.cover_img = self.images_manager.read_image(item.href) diff --git a/src/calibre/ebooks/docx/writer/images.py b/src/calibre/ebooks/docx/writer/images.py index a77a79efb0..4ae6cbb334 100644 --- a/src/calibre/ebooks/docx/writer/images.py +++ b/src/calibre/ebooks/docx/writer/images.py @@ -9,7 +9,7 @@ import posixpath from collections import namedtuple from functools import partial -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from lxml import etree @@ -34,7 +34,7 @@ def get_image_margins(style): ans = {} for edge in 'Left Right Top Bottom'.split(): val = as_num(getattr(style, 'padding' + edge)) + as_num(getattr(style, 'margin' + edge)) - ans['dist' + edge[0]] = unicode_type(pt_to_emu(val)) + ans['dist' + edge[0]] = str(pt_to_emu(val)) return ans @@ -131,7 +131,7 @@ def create_image_markup(self, html_img, stylizer, href, as_block=False): makeelement(parent, 'wp:simplePos', x='0', y='0') makeelement(makeelement(parent, 'wp:positionH', relativeFrom='margin'), 'wp:align').text = floating makeelement(makeelement(parent, 'wp:positionV', relativeFrom='line'), 'wp:align').text = 'top' - makeelement(parent, 'wp:extent', cx=unicode_type(width), cy=unicode_type(height)) + makeelement(parent, 'wp:extent', cx=str(width), cy=str(height)) if fake_margins: # DOCX does not support setting margins for inline images, so we # fake it by using effect extents to simulate margins @@ -149,7 +149,7 @@ def create_image_markup(self, html_img, stylizer, href, as_block=False): def create_docx_image_markup(self, parent, name, alt, img_rid, width, height): makeelement, namespaces = self.document_relationships.namespace.makeelement, self.document_relationships.namespace.namespaces - makeelement(parent, 'wp:docPr', id=unicode_type(self.count), name=name, descr=alt) + makeelement(parent, 'wp:docPr', id=str(self.count), name=name, descr=alt) makeelement(makeelement(parent, 'wp:cNvGraphicFramePr'), 'a:graphicFrameLocks', noChangeAspect="1") g = makeelement(parent, 'a:graphic') gd = makeelement(g, 'a:graphicData', uri=namespaces['pic']) @@ -162,7 +162,7 @@ def create_docx_image_markup(self, parent, name, alt, img_rid, width, height): makeelement(makeelement(bf, 'a:stretch'), 'a:fillRect') spPr = makeelement(pic, 'pic:spPr') xfrm = makeelement(spPr, 'a:xfrm') - makeelement(xfrm, 'a:off', x='0', y='0'), makeelement(xfrm, 'a:ext', cx=unicode_type(width), cy=unicode_type(height)) + makeelement(xfrm, 'a:off', x='0', y='0'), makeelement(xfrm, 'a:ext', cx=str(width), cy=str(height)) makeelement(makeelement(spPr, 'a:prstGeom', prst='rect'), 'a:avLst') def create_filename(self, href, fmt): @@ -173,7 +173,7 @@ def create_filename(self, href, fmt): base = fname while fname.lower() in self.seen_filenames: num += 1 - fname = base + unicode_type(num) + fname = base + str(num) self.seen_filenames.add(fname.lower()) fname += os.extsep + fmt.lower() return fname @@ -208,7 +208,7 @@ def create_cover_markup(self, img, preserve_aspect_ratio, width, height): makeelement(makeelement(parent, 'wp:positionH', relativeFrom='page'), 'wp:align').text = 'center' makeelement(makeelement(parent, 'wp:positionV', relativeFrom='page'), 'wp:align').text = 'center' width, height = map(pt_to_emu, (width, height)) - makeelement(parent, 'wp:extent', cx=unicode_type(width), cy=unicode_type(height)) + makeelement(parent, 'wp:extent', cx=str(width), cy=str(height)) makeelement(parent, 'wp:effectExtent', l='0', r='0', t='0', b='0') makeelement(parent, 'wp:wrapTopAndBottom') self.create_docx_image_markup(parent, 'cover.jpg', _('Cover'), img.rid, width, height) diff --git a/src/calibre/ebooks/docx/writer/links.py b/src/calibre/ebooks/docx/writer/links.py index 6b0825a544..71e5eadf83 100644 --- a/src/calibre/ebooks/docx/writer/links.py +++ b/src/calibre/ebooks/docx/writer/links.py @@ -10,7 +10,6 @@ from calibre.ebooks.oeb.base import urlquote from calibre.utils.filenames import ascii_text -from polyglot.builtins import unicode_type from polyglot.urllib import urlparse @@ -37,7 +36,7 @@ def serialize(self, body, makeelement): p = makeelement(body, 'w:p', append=False) ppr = makeelement(p, 'w:pPr') makeelement(ppr, 'w:pStyle', w_val="Normal") - makeelement(ppr, 'w:ind', w_left='0', w_firstLineChars='0', w_firstLine='0', w_leftChars=unicode_type(200 * self.level)) + makeelement(ppr, 'w:ind', w_left='0', w_firstLineChars='0', w_firstLine='0', w_leftChars=str(200 * self.level)) if self.is_first: makeelement(ppr, 'w:pageBreakBefore', w_val='off') r = makeelement(p, 'w:r') @@ -71,7 +70,7 @@ def __init__(self, namespace, document_relationships, log): self.namespace = namespace self.log = log self.document_relationships = document_relationships - self.top_anchor = unicode_type(uuid4().hex) + self.top_anchor = str(uuid4().hex) self.anchor_map = {} self.used_bookmark_names = set() self.bmark_id = 0 diff --git a/src/calibre/ebooks/docx/writer/lists.py b/src/calibre/ebooks/docx/writer/lists.py index db0a3f17df..f28ba17781 100644 --- a/src/calibre/ebooks/docx/writer/lists.py +++ b/src/calibre/ebooks/docx/writer/lists.py @@ -8,7 +8,7 @@ from collections import defaultdict from operator import attrgetter -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues LIST_STYLES = frozenset( 'disc circle square decimal decimal-leading-zero lower-roman upper-roman' @@ -83,7 +83,7 @@ def link_blocks(self): def serialize(self, parent): makeelement = self.namespace.makeelement - an = makeelement(parent, 'w:abstractNum', w_abstractNumId=unicode_type(self.num_id)) + an = makeelement(parent, 'w:abstractNum', w_abstractNumId=str(self.num_id)) makeelement(an, 'w:multiLevelType', w_val='hybridMultilevel') makeelement(an, 'w:name', w_val='List %d' % (self.num_id + 1)) for level in self.levels: @@ -114,12 +114,12 @@ def __hash__(self): return hash((self.start, self.num_fmt, self.lvl_text)) def serialize(self, parent, makeelement): - lvl = makeelement(parent, 'w:lvl', w_ilvl=unicode_type(self.ilvl)) - makeelement(lvl, 'w:start', w_val=unicode_type(self.start)) + lvl = makeelement(parent, 'w:lvl', w_ilvl=str(self.ilvl)) + makeelement(lvl, 'w:start', w_val=str(self.start)) makeelement(lvl, 'w:numFmt', w_val=self.num_fmt) makeelement(lvl, 'w:lvlText', w_val=self.lvl_text) makeelement(lvl, 'w:lvlJc', w_val='left') - makeelement(makeelement(lvl, 'w:pPr'), 'w:ind', w_hanging='360', w_left=unicode_type(1152 + self.ilvl * 360)) + makeelement(makeelement(lvl, 'w:pPr'), 'w:ind', w_hanging='360', w_left=str(1152 + self.ilvl * 360)) if self.num_fmt == 'bullet': ff = {'\uf0b7':'Symbol', '\uf0a7':'Wingdings'}.get(self.lvl_text, 'Courier New') makeelement(makeelement(lvl, 'w:rPr'), 'w:rFonts', w_ascii=ff, w_hAnsi=ff, w_hint="default") @@ -165,5 +165,5 @@ def serialize(self, parent): defn.serialize(parent) makeelement = self.namespace.makeelement for defn in self.definitions: - n = makeelement(parent, 'w:num', w_numId=unicode_type(defn.num_id + 1)) - makeelement(n, 'w:abstractNumId', w_val=unicode_type(defn.num_id)) + n = makeelement(parent, 'w:num', w_numId=str(defn.num_id + 1)) + makeelement(n, 'w:abstractNumId', w_val=str(defn.num_id)) diff --git a/src/calibre/ebooks/docx/writer/styles.py b/src/calibre/ebooks/docx/writer/styles.py index ac2606c7d6..5a57c6d279 100644 --- a/src/calibre/ebooks/docx/writer/styles.py +++ b/src/calibre/ebooks/docx/writer/styles.py @@ -14,7 +14,7 @@ from calibre.ebooks import parse_css_length from calibre.ebooks.docx.writer.utils import convert_color, int_or_zero from calibre.utils.localization import lang_as_iso639_1 -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from tinycss.css21 import CSS21Parser css_parser = CSS21Parser() @@ -76,7 +76,7 @@ def serialize(self, styles, normal_style): pPr = makeelement(block, 'w:pPr') self.bs.serialize_properties(pPr, normal_style.bs) if self.outline_level is not None: - makeelement(pPr, 'w:outlineLvl', w_val=unicode_type(self.outline_level + 1)) + makeelement(pPr, 'w:outlineLvl', w_val=str(self.outline_level + 1)) rPr = makeelement(block, 'w:rPr') self.rs.serialize_properties(rPr, normal_style.rs) @@ -109,16 +109,16 @@ def __init__(self, namespace, html_tag, tag_style): def serialize(self, block, parent): if self.is_dropcaps: - attrs = dict(w_dropCap='drop', w_lines=unicode_type(self.dropcaps_lines), w_wrap='around', w_vAnchor='text', w_hAnchor='text') + attrs = dict(w_dropCap='drop', w_lines=str(self.dropcaps_lines), w_wrap='around', w_vAnchor='text', w_hAnchor='text') else: attrs = dict( w_wrap='around', w_vAnchor='text', w_hAnchor='text', w_xAlign=self.x_align, w_y='1', - w_hSpace=unicode_type(self.h_space), w_vSpace=unicode_type(self.v_space), w_hRule=self.h_rule + w_hSpace=str(self.h_space), w_vSpace=str(self.v_space), w_hRule=self.h_rule ) if self.w is not None: - attrs['w_w'] = unicode_type(self.w) + attrs['w_w'] = str(self.w) if self.h is not None: - attrs['w_h'] = unicode_type(self.h) + attrs['w_h'] = str(self.h) self.makeelement(parent, 'w:framePr', **attrs) # Margins are already applied by the frame style, so override them to # be zero on individual blocks @@ -138,7 +138,7 @@ def serialize(self, block, parent): width = getattr(self, 'border_%s_width' % edge) bstyle = getattr(self, 'border_%s_style' % edge) self.makeelement( - bdr, 'w:'+edge, w_space=unicode_type(padding), w_val=bstyle, w_sz=unicode_type(width), w_color=getattr(self, 'border_%s_color' % edge)) + bdr, 'w:'+edge, w_space=str(padding), w_val=bstyle, w_sz=str(width), w_color=getattr(self, 'border_%s_color' % edge)) class DOCXStyle: @@ -234,7 +234,7 @@ def __init__(self, namespace, css, is_parent_style=False): self.spacing = None va = css.first_vertical_align if isinstance(va, numbers.Number): - self.vertical_align = unicode_type(int(va * 2)) + self.vertical_align = str(int(va * 2)) else: val = { 'top':'superscript', 'text-top':'superscript', 'sup':'superscript', 'super':'superscript', @@ -290,9 +290,9 @@ def serialize_borders(self, bdr, normal_style): w = self.w is_normal_style = self is normal_style if is_normal_style or self.padding != normal_style.padding: - bdr.set(w('space'), unicode_type(self.padding)) + bdr.set(w('space'), str(self.padding)) if is_normal_style or self.border_width != normal_style.border_width: - bdr.set(w('sz'), unicode_type(self.border_width)) + bdr.set(w('sz'), str(self.border_width)) if is_normal_style or self.border_style != normal_style.border_style: bdr.set(w('val'), self.border_style) if is_normal_style or self.border_color != normal_style.border_color: @@ -342,7 +342,7 @@ def check_attr(attr): if check_attr('shadow'): rPr.append(makeelement(rPr, 'shadow', val=bmap(self.shadow))) if check_attr('spacing'): - rPr.append(makeelement(rPr, 'spacing', val=unicode_type(self.spacing or 0))) + rPr.append(makeelement(rPr, 'spacing', val=str(self.spacing or 0))) if is_normal_style: rPr.append(makeelement(rPr, 'vertAlign', val=self.vertical_align if self.vertical_align in {'superscript', 'subscript'} else 'baseline')) elif self.vertical_align != normal_style.vertical_align: @@ -380,7 +380,7 @@ def check(attr): for name, attr in (('sz', 'font_size'), ('b', 'bold'), ('i', 'italic')): pval, cval = vals(attr) if pval != cval: - val = 'on' if attr in {'bold', 'italic'} else unicode_type(cval) # bold, italic are toggle properties + val = 'on' if attr in {'bold', 'italic'} else str(cval) # bold, italic are toggle properties for suffix in ('', 'Cs'): add(name + suffix, val=val) @@ -401,7 +401,7 @@ def check(attr): if check('shadow'): add('shadow', val='on') # toggle property if check('spacing'): - add('spacing', val=unicode_type(child_style.spacing or 0)) + add('spacing', val=str(child_style.spacing or 0)) if check('vertical_align'): val = child_style.vertical_align if val in {'superscript', 'subscript', 'baseline'}: @@ -411,9 +411,9 @@ def check(attr): bdr = {} if check('padding'): - bdr['space'] = unicode_type(child_style.padding) + bdr['space'] = str(child_style.padding) if check('border_width'): - bdr['sz'] = unicode_type(child_style.border_width) + bdr['sz'] = str(child_style.border_width) if check('border_style'): bdr['val'] = child_style.border_style if check('border_color'): @@ -537,14 +537,14 @@ def serialize_borders(self, bdr, normal_style): e = bdr.makeelement(w(edge)) padding = getattr(self, 'padding_' + edge) if (self is normal_style and padding > 0) or (padding != getattr(normal_style, 'padding_' + edge)): - e.set(w('space'), unicode_type(padding)) + e.set(w('space'), str(padding)) width = getattr(self, 'border_%s_width' % edge) bstyle = getattr(self, 'border_%s_style' % edge) if (self is normal_style and width > 0 and bstyle != 'none' ) or width != getattr(normal_style, 'border_%s_width' % edge ) or bstyle != getattr(normal_style, 'border_%s_style' % edge): e.set(w('val'), bstyle) - e.set(w('sz'), unicode_type(width)) + e.set(w('sz'), str(width)) e.set(w('color'), getattr(self, 'border_%s_color' % edge)) if e.attrib: bdr.append(e) @@ -568,15 +568,15 @@ def serialize_properties(self, pPr, normal_style): if css_unit in ('em', 'ex'): lines = max(0, int(css_val * (50 if css_unit == 'ex' else 100))) if (self is normal_style and lines > 0) or getter(self) != getter(normal_style): - spacing.set(w(attr + 'Lines'), unicode_type(lines)) + spacing.set(w(attr + 'Lines'), str(lines)) else: getter = attrgetter('margin_' + edge) val = getter(self) if (self is normal_style and val > 0) or val != getter(normal_style): - spacing.set(w(attr), unicode_type(val)) + spacing.set(w(attr), str(val)) if self is normal_style or self.line_height != normal_style.line_height: - spacing.set(w('line'), unicode_type(self.line_height)) + spacing.set(w('line'), str(self.line_height)) spacing.set(w('lineRule'), 'atLeast') if spacing.attrib: @@ -589,31 +589,31 @@ def serialize_properties(self, pPr, normal_style): if css_unit in ('em', 'ex'): chars = max(0, int(css_val * (50 if css_unit == 'ex' else 100))) if (self is normal_style and chars > 0) or getter(self) != getter(normal_style): - ind.set(w(edge + 'Chars'), unicode_type(chars)) + ind.set(w(edge + 'Chars'), str(chars)) else: getter = attrgetter('margin_' + edge) val = getter(self) if (self is normal_style and val > 0) or val != getter(normal_style): - ind.set(w(edge), unicode_type(val)) + ind.set(w(edge), str(val)) ind.set(w(edge + 'Chars'), '0') # This is needed to override any declaration in the parent style css_val, css_unit = parse_css_length(self.css_text_indent) if css_unit in ('em', 'ex'): chars = int(css_val * (50 if css_unit == 'ex' else 100)) if css_val >= 0: if (self is normal_style and chars > 0) or self.css_text_indent != normal_style.css_text_indent: - ind.set(w('firstLineChars'), unicode_type(chars)) + ind.set(w('firstLineChars'), str(chars)) else: if (self is normal_style and chars < 0) or self.css_text_indent != normal_style.css_text_indent: - ind.set(w('hangingChars'), unicode_type(abs(chars))) + ind.set(w('hangingChars'), str(abs(chars))) else: val = self.text_indent if val >= 0: if (self is normal_style and val > 0) or self.text_indent != normal_style.text_indent: - ind.set(w('firstLine'), unicode_type(val)) + ind.set(w('firstLine'), str(val)) ind.set(w('firstLineChars'), '0') # This is needed to override any declaration in the parent style else: if (self is normal_style and val < 0) or self.text_indent != normal_style.text_indent: - ind.set(w('hanging'), unicode_type(abs(val))) + ind.set(w('hanging'), str(abs(val))) ind.set(w('hangingChars'), '0') if ind.attrib: pPr.append(ind) @@ -687,7 +687,7 @@ def finalize(self, all_blocks): pure_block_styles.add(bs) self.pure_block_styles = sorted(pure_block_styles, key=block_counts.__getitem__) - bnum = len(unicode_type(max(1, len(pure_block_styles) - 1))) + bnum = len(str(max(1, len(pure_block_styles) - 1))) for i, bs in enumerate(self.pure_block_styles): bs.id = bs.name = '%0{}d Block'.format(bnum) % i bs.seq = i @@ -707,7 +707,7 @@ def finalize(self, all_blocks): heading_style = styles[-1] heading_style.outline_level = i - snum = len(unicode_type(max(1, len(counts) - 1))) + snum = len(str(max(1, len(counts) - 1))) heading_styles = [] for i, (style, count) in enumerate(counts.most_common()): if i == 0: @@ -735,7 +735,7 @@ def finalize(self, all_blocks): if run.descendant_style is None: run.descendant_style = descendant_style_map[ds] = ds ds_counts[run.descendant_style] += run.style_weight - rnum = len(unicode_type(max(1, len(ds_counts) - 1))) + rnum = len(str(max(1, len(ds_counts) - 1))) for i, (text_style, count) in enumerate(ds_counts.most_common()): text_style.id = 'Text%d' % i text_style.name = '%0{}d Text'.format(rnum) % i diff --git a/src/calibre/ebooks/docx/writer/tables.py b/src/calibre/ebooks/docx/writer/tables.py index 3232f3b42a..8141448333 100644 --- a/src/calibre/ebooks/docx/writer/tables.py +++ b/src/calibre/ebooks/docx/writer/tables.py @@ -9,7 +9,7 @@ from calibre.ebooks.docx.writer.utils import convert_color from calibre.ebooks.docx.writer.styles import read_css_block_borders as rcbb, border_edges -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class Dummy: @@ -115,7 +115,7 @@ def add_table(self, table): def serialize(self, parent, makeelement): tc = makeelement(parent, 'w:tc') tcPr = makeelement(tc, 'w:tcPr') - makeelement(tcPr, 'w:tcW', w_type=self.width[0], w_w=unicode_type(self.width[1])) + makeelement(tcPr, 'w:tcW', w_type=self.width[0], w_w=str(self.width[1])) # For some reason, Word 2007 refuses to honor at the table or row # level, despite what the specs say, so we inherit and apply at the # cell level @@ -126,7 +126,7 @@ def serialize(self, parent, makeelement): b = makeelement(tcPr, 'w:tcBorders', append=False) for edge, border in iteritems(self.borders): if border is not None and border.width > 0 and border.style != 'none': - makeelement(b, 'w:' + edge, w_val=border.style, w_sz=unicode_type(border.width), w_color=border.color) + makeelement(b, 'w:' + edge, w_val=border.style, w_sz=str(border.width), w_color=border.color) if len(b) > 0: tcPr.append(b) @@ -136,7 +136,7 @@ def serialize(self, parent, makeelement): if edge in {'top', 'bottom'} or (edge == 'left' and self is self.row.first_cell) or (edge == 'right' and self is self.row.last_cell): padding += getattr(self.row, 'padding_' + edge) if padding > 0: - makeelement(m, 'w:' + edge, w_type='dxa', w_w=unicode_type(int(padding * 20))) + makeelement(m, 'w:' + edge, w_type='dxa', w_w=str(int(padding * 20))) if len(m) > 0: tcPr.append(m) @@ -356,14 +356,14 @@ def serialize(self, parent): return tbl = makeelement(parent, 'w:tbl') tblPr = makeelement(tbl, 'w:tblPr') - makeelement(tblPr, 'w:tblW', w_type=self.width[0], w_w=unicode_type(self.width[1])) + makeelement(tblPr, 'w:tblW', w_type=self.width[0], w_w=str(self.width[1])) if self.float in {'left', 'right'}: kw = {'w_vertAnchor':'text', 'w_horzAnchor':'text', 'w_tblpXSpec':self.float} for edge in border_edges: val = getattr(self, 'margin_' + edge) or 0 if {self.float, edge} == {'left', 'right'}: val = max(val, 2) - kw['w_' + edge + 'FromText'] = unicode_type(max(0, int(val *20))) + kw['w_' + edge + 'FromText'] = str(max(0, int(val *20))) makeelement(tblPr, 'w:tblpPr', **kw) if self.jc is not None: makeelement(tblPr, 'w:jc', w_val=self.jc) diff --git a/src/calibre/ebooks/epub/cfi/tests.py b/src/calibre/ebooks/epub/cfi/tests.py index c97317ee85..e8f92be52e 100644 --- a/src/calibre/ebooks/epub/cfi/tests.py +++ b/src/calibre/ebooks/epub/cfi/tests.py @@ -8,7 +8,7 @@ import unittest, numbers from calibre.ebooks.epub.cfi.parse import parser, cfi_sort_key, decode_cfi -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class Tests(unittest.TestCase): @@ -59,7 +59,7 @@ def a(before=None, after=None, **params): if after is not None: ta['after'] = after if params: - ta['params'] = {unicode_type(k):(v,) if isinstance(v, unicode_type) else v for k, v in iteritems(params)} + ta['params'] = {str(k):(v,) if isinstance(v, str) else v for k, v in iteritems(params)} if ta: step['text_assertion'] = ta return ans diff --git a/src/calibre/ebooks/epub/pages.py b/src/calibre/ebooks/epub/pages.py index ed824d0a44..da06eef01e 100644 --- a/src/calibre/ebooks/epub/pages.py +++ b/src/calibre/ebooks/epub/pages.py @@ -12,7 +12,6 @@ from calibre.ebooks.oeb.base import XHTML_NS from calibre.ebooks.oeb.base import OEBBook from lxml.etree import XPath -from polyglot.builtins import unicode_type NSMAP = {'h': XHTML_NS, 'html': XHTML_NS, 'xhtml': XHTML_NS} PAGE_RE = re.compile(r'page', re.IGNORECASE) @@ -32,7 +31,7 @@ def filter_name(name): def build_name_for(expr): if not expr: counter = count(1) - return lambda elem: unicode_type(next(counter)) + return lambda elem: str(next(counter)) selector = XPath(expr, namespaces=NSMAP) def name_for(elem): diff --git a/src/calibre/ebooks/epub/periodical.py b/src/calibre/ebooks/epub/periodical.py index dc6f7a0786..6efdbe3c3d 100644 --- a/src/calibre/ebooks/epub/periodical.py +++ b/src/calibre/ebooks/epub/periodical.py @@ -12,7 +12,6 @@ from calibre.constants import __appname__, __version__ from calibre import strftime, prepare_string_for_xml as xml from calibre.utils.date import parse_date -from polyglot.builtins import unicode_type SONY_METADATA = '''\ @@ -83,21 +82,21 @@ def sony_metadata(oeb): m = oeb.metadata - title = short_title = unicode_type(m.title[0]) + title = short_title = str(m.title[0]) publisher = __appname__ + ' ' + __version__ try: - pt = unicode_type(oeb.metadata.publication_type[0]) + pt = str(oeb.metadata.publication_type[0]) short_title = ':'.join(pt.split(':')[2:]) except: pass try: - date = parse_date(unicode_type(m.date[0]), + date = parse_date(str(m.date[0]), as_utc=False).strftime('%Y-%m-%d') except: date = strftime('%Y-%m-%d') try: - language = unicode_type(m.language[0]).replace('_', '-') + language = str(m.language[0]).replace('_', '-') except: language = 'en' short_title = xml(short_title, True) @@ -115,9 +114,9 @@ def cal_id(x): return True try: - base_id = unicode_type(list(filter(cal_id, m.identifier))[0]) + base_id = str(list(filter(cal_id, m.identifier))[0]) except: - base_id = unicode_type(uuid4()) + base_id = str(uuid4()) toc = oeb.toc @@ -130,7 +129,7 @@ def cal_id(x): for x in toc: section.nodes.append(x) toc = TOC(klass='periodical', href=oeb.spine[2].href, - title=unicode_type(oeb.metadata.title[0])) + title=str(oeb.metadata.title[0])) toc.nodes.append(section) entries = [] @@ -145,7 +144,7 @@ def cal_id(x): d = 1 bsectitle = sectitle while sectitle in seen_titles: - sectitle = bsectitle + ' ' + unicode_type(d) + sectitle = bsectitle + ' ' + str(d) d += 1 seen_titles.add(sectitle) sectitle = xml(sectitle, True) @@ -164,7 +163,7 @@ def cal_id(x): btitle = atitle d = 1 while atitle in seen_titles: - atitle = btitle + ' ' + unicode_type(d) + atitle = btitle + ' ' + str(d) d += 1 auth = article.author if article.author else '' @@ -181,7 +180,7 @@ def cal_id(x): short_title=short_title, section_title=sectitle, href=article.href, - word_count=unicode_type(1), + word_count=str(1), id=xml(base_id)+'/'+secid+'/'+aid )) diff --git a/src/calibre/ebooks/fb2/fb2ml.py b/src/calibre/ebooks/fb2/fb2ml.py index 952a32e0be..d7771afe87 100644 --- a/src/calibre/ebooks/fb2/fb2ml.py +++ b/src/calibre/ebooks/fb2/fb2ml.py @@ -20,7 +20,7 @@ from calibre.utils.xml_parse import safe_xml_fromstring from calibre.utils.img import save_cover_data_to from calibre.ebooks.oeb.base import urlnormalize -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes from polyglot.binary import as_base64_unicode from polyglot.urllib import urlparse @@ -154,7 +154,7 @@ def fb2_header(self): metadata['author'] = '' metadata['keywords'] = '' - tags = list(map(unicode_type, self.oeb_book.metadata.subject)) + tags = list(map(str, self.oeb_book.metadata.subject)) if tags: tags = ', '.join(prepare_string_for_xml(x) for x in tags) metadata['keywords'] = '%s'%tags @@ -169,12 +169,12 @@ def fb2_header(self): year = publisher = isbn = '' identifiers = self.oeb_book.metadata['identifier'] for x in identifiers: - if x.get(OPF('scheme'), None).lower() == 'uuid' or unicode_type(x).startswith('urn:uuid:'): - metadata['id'] = unicode_type(x).split(':')[-1] + if x.get(OPF('scheme'), None).lower() == 'uuid' or str(x).startswith('urn:uuid:'): + metadata['id'] = str(x).split(':')[-1] break if metadata['id'] is None: self.log.warn('No UUID identifier found') - metadata['id'] = unicode_type(uuid.uuid4()) + metadata['id'] = str(uuid.uuid4()) try: date = self.oeb_book.metadata['date'][0] @@ -236,7 +236,7 @@ def fb2_header(self): ''') % metadata # Remove empty lines. - return '\n'.join(filter(unicode_type.strip, header.splitlines())) + return '\n'.join(filter(str.strip, header.splitlines())) def fb2_footer(self): return '' @@ -247,8 +247,8 @@ def get_cover(self): cover_href = None # Get the raster cover if it's available. - if self.oeb_book.metadata.cover and unicode_type(self.oeb_book.metadata.cover[0]) in self.oeb_book.manifest.ids: - id = unicode_type(self.oeb_book.metadata.cover[0]) + if self.oeb_book.metadata.cover and str(self.oeb_book.metadata.cover[0]) in self.oeb_book.manifest.ids: + id = str(self.oeb_book.metadata.cover[0]) cover_item = self.oeb_book.manifest.ids[id] if cover_item.media_type in OEB_RASTER_IMAGES: cover_href = cover_item.href diff --git a/src/calibre/ebooks/html/input.py b/src/calibre/ebooks/html/input.py index ed652fedb0..2622ab6104 100644 --- a/src/calibre/ebooks/html/input.py +++ b/src/calibre/ebooks/html/input.py @@ -17,7 +17,6 @@ from calibre.ebooks.chardet import detect_xml_encoding from calibre.constants import iswindows from calibre import unicode_path, as_unicode, replace_entities -from polyglot.builtins import unicode_type from polyglot.urllib import urlparse, urlunparse @@ -46,7 +45,7 @@ def __init__(self, url, base): :param base: The base folder that relative URLs are with respect to. Must be a unicode string. ''' - assert isinstance(url, unicode_type) and isinstance(base, unicode_type) + assert isinstance(url, str) and isinstance(base, str) self.url = url self.parsed_url = urlparse(self.url) self.is_local = self.parsed_url.scheme in ('', 'file') @@ -155,7 +154,7 @@ def __str__(self): return 'HTMLFile:%d:%s:%r'%(self.level, 'b' if self.is_binary else 'a', self.path) def __repr__(self): - return unicode_type(self) + return str(self) def find_links(self, src): for match in self.LINK_PAT.finditer(src): diff --git a/src/calibre/ebooks/html/to_zip.py b/src/calibre/ebooks/html/to_zip.py index be8a7b5e8f..9f7dc613cb 100644 --- a/src/calibre/ebooks/html/to_zip.py +++ b/src/calibre/ebooks/html/to_zip.py @@ -10,7 +10,6 @@ from calibre.customize import FileTypePlugin from calibre.constants import numeric_version -from polyglot.builtins import unicode_type class HTML2ZIP(FileTypePlugin): @@ -114,7 +113,7 @@ def size_dialog(): config_dialog.exec_() if config_dialog.result() == QDialog.DialogCode.Accepted: - sc = unicode_type(sc.text()).strip() + sc = str(sc.text()).strip() if bf.isChecked(): sc += '|bf' customize_plugin(self, sc) diff --git a/src/calibre/ebooks/htmlz/oeb2html.py b/src/calibre/ebooks/htmlz/oeb2html.py index 7335739cfe..027d42bd84 100644 --- a/src/calibre/ebooks/htmlz/oeb2html.py +++ b/src/calibre/ebooks/htmlz/oeb2html.py @@ -20,7 +20,7 @@ XHTML, XHTML_NS, SVG_NS, barename, namespace, OEB_IMAGES, XLINK, rewrite_links, urlnormalize) from calibre.ebooks.oeb.stylizer import Stylizer from calibre.utils.logging import default_log -from polyglot.builtins import unicode_type, string_or_bytes, as_unicode +from polyglot.builtins import string_or_bytes, as_unicode from polyglot.urllib import urldefrag SELF_CLOSING_TAGS = {'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta'} @@ -46,7 +46,7 @@ def oeb2html(self, oeb_book, opts): self.log.info('Converting OEB book to HTML...') self.opts = opts try: - self.book_title = unicode_type(oeb_book.metadata.title[0]) + self.book_title = str(oeb_book.metadata.title[0]) except Exception: self.book_title = _('Unknown') self.links = {} diff --git a/src/calibre/ebooks/lit/reader.py b/src/calibre/ebooks/lit/reader.py index f51fa50ca3..585f504e2b 100644 --- a/src/calibre/ebooks/lit/reader.py +++ b/src/calibre/ebooks/lit/reader.py @@ -17,7 +17,7 @@ from calibre.ebooks.oeb.base import urlnormalize, xpath from calibre.ebooks.oeb.reader import OEBReader from calibre.ebooks import DRMError -from polyglot.builtins import codepoint_to_chr, unicode_type, string_or_bytes, itervalues +from polyglot.builtins import codepoint_to_chr, string_or_bytes, itervalues from polyglot.urllib import unquote as urlunquote, urldefrag from calibre_extensions import lzx, msdes @@ -121,7 +121,7 @@ def consume_sized_utf8_string(bytes, zpad=False): def encode(string): - return unicode_type(string).encode('ascii', 'xmlcharrefreplace') + return str(string).encode('ascii', 'xmlcharrefreplace') class UnBinary: @@ -325,7 +325,7 @@ def binary_to_text_inner(self, bin, buf, stack): c = '"' elif c == '<': c = '<' - if isinstance(c, unicode_type): + if isinstance(c, str): c = c.encode('ascii', 'xmlcharrefreplace') buf.write(c) count -= 1 diff --git a/src/calibre/ebooks/lit/writer.py b/src/calibre/ebooks/lit/writer.py index f4e9c9a497..689f04a0eb 100644 --- a/src/calibre/ebooks/lit/writer.py +++ b/src/calibre/ebooks/lit/writer.py @@ -29,7 +29,7 @@ import calibre from calibre_extensions import msdes import calibre.ebooks.lit.mssha1 as mssha1 -from polyglot.builtins import codepoint_to_chr, unicode_type, string_or_bytes, native_string_type +from polyglot.builtins import codepoint_to_chr, string_or_bytes, native_string_type from polyglot.urllib import urldefrag, unquote __all__ = ['LitWriter'] @@ -283,7 +283,7 @@ def build_ahc(self): data.write(codepoint_to_chr(len(self.anchors)).encode('utf-8')) for anchor, offset in self.anchors: data.write(codepoint_to_chr(len(anchor)).encode('utf-8')) - if isinstance(anchor, unicode_type): + if isinstance(anchor, str): anchor = anchor.encode('utf-8') data.write(anchor) data.write(pack(' 0 and self.link_level <= self.link_levels: for path in paths: @@ -358,7 +358,7 @@ def preprocess(self, raw): os.makedirs(tdir) try: with open(os.path.join(tdir, 'html2lrf-verbose.html'), 'wb') as f: - f.write(unicode_type(soup).encode('utf-8')) + f.write(str(soup).encode('utf-8')) self.log.info(_('Written preprocessed HTML to ')+f.name) except: pass @@ -391,7 +391,7 @@ def add_file(self, path): self.log.info(_('\tConverting to BBeB...')) self.current_style = {} self.page_break_found = False - if not isinstance(path, unicode_type): + if not isinstance(path, str): path = path.decode(sys.getfilesystemencoding()) self.target_prefix = path self.previous_text = '\n' @@ -401,7 +401,7 @@ def add_file(self, path): def parse_css(self, style): """ Parse the contents of a \n' objects += '\n' if write_files: diff --git a/src/calibre/ebooks/lrf/lrs/convert_from.py b/src/calibre/ebooks/lrf/lrs/convert_from.py index 6fc763f485..026643c1fd 100644 --- a/src/calibre/ebooks/lrf/lrs/convert_from.py +++ b/src/calibre/ebooks/lrf/lrs/convert_from.py @@ -22,7 +22,7 @@ TextStyle ) from calibre.utils.config import OptionParser -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes class LrsParser: @@ -55,7 +55,7 @@ def attrs_to_dict(cls, tag, exclude=('objid',)): for key, val in tag.attrs: if key in exclude: continue - result[unicode_type(key)] = val + result[str(key)] = val return result def text_tag_to_element(self, tag): diff --git a/src/calibre/ebooks/lrf/meta.py b/src/calibre/ebooks/lrf/meta.py index a003b82db6..14aeae303e 100644 --- a/src/calibre/ebooks/lrf/meta.py +++ b/src/calibre/ebooks/lrf/meta.py @@ -22,7 +22,7 @@ from calibre.ebooks.chardet import xml_to_unicode from calibre.utils.cleantext import clean_xml_chars from calibre.ebooks.metadata import MetaInformation, string_to_authors -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes BYTE = "\n' - s += unicode_type(self.content) + s += str(self.content) s += '\n'%(self.name,) return s return s.rstrip() + ' />\n' @@ -710,7 +709,7 @@ class Span(TextTag): lineposition_map = {1:'before', 2:'after'} def add_text(self, text): - s = unicode_type(text, "utf-16-le") + s = str(text, "utf-16-le") if s: s = s.translate(self.text_map) self.content.append(self.entity_pattern.sub(entity_to_unicode, s)) @@ -850,7 +849,7 @@ def find_first_tag(start): self.add_text(stream.read(tag.word)) elif tag.id in self.__class__.text_tags: # A Text tag action = self.__class__.text_tags[tag.id] - if isinstance(action, unicode_type): + if isinstance(action, str): getattr(self, action)(tag, stream) else: getattr(self, action[0])(tag, action[1]) @@ -874,14 +873,14 @@ def __str__(self): s = '' open_containers = collections.deque() for c in self.content: - if isinstance(c, unicode_type): + if isinstance(c, str): s += prepare_string_for_xml(c).replace('\0', '') elif c is None: if open_containers: p = open_containers.pop() s += ''%(p.name,) else: - s += unicode_type(c) + s += str(c) if not c.self_closing: open_containers.append(c) @@ -897,7 +896,7 @@ def to_html(self): open_containers = collections.deque() in_p = False for c in self.content: - if isinstance(c, unicode_type): + if isinstance(c, str): s += c elif c is None: p = open_containers.pop() @@ -992,7 +991,7 @@ def __str__(self): s += '%s="%s" '%(attr, self.attrs[attr]) s = s.rstrip() + '>\n' for po in self: - s += unicode_type(po) + '\n' + s += str(po) + '\n' s += '\n'%(self.__class__.__name__,) return s @@ -1025,7 +1024,7 @@ class ImageStream(LRFStream): def end_stream(self, *args): LRFStream.end_stream(self, *args) - self.file = unicode_type(self.id) + '.' + self.encoding.lower() + self.file = str(self.id) + '.' + self.encoding.lower() if self._document is not None: self._document.image_map[self.id] = self @@ -1189,7 +1188,7 @@ def __str__(self): s += '\n'%\ (self.binding_map[doc.binding], doc.dpi, doc.width, doc.height, doc.color_depth) for font in self._document.font_map.values(): - s += unicode_type(font) + s += str(font) s += '\n' return s @@ -1230,7 +1229,7 @@ def __iter__(self): def __str__(self): s = '\n' for i in self: - s += unicode_type(i) + s += str(i) return s + '\n' diff --git a/src/calibre/ebooks/lrf/pylrs/elements.py b/src/calibre/ebooks/lrf/pylrs/elements.py index f38c2253b1..5a6a786767 100644 --- a/src/calibre/ebooks/lrf/pylrs/elements.py +++ b/src/calibre/ebooks/lrf/pylrs/elements.py @@ -2,7 +2,7 @@ """ elements.py -- replacements and helpers for ElementTree """ -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes class ElementWriter: @@ -25,9 +25,9 @@ def _encodeCdata(self, rawText): return text def _writeAttribute(self, f, name, value): - f.write(' %s="' % unicode_type(name)) + f.write(' %s="' % str(name)) if not isinstance(value, string_or_bytes): - value = unicode_type(value) + value = str(value) value = self._encodeCdata(value) value = value.replace('"', '"') f.write(value) @@ -38,7 +38,7 @@ def _writeText(self, f, rawText): f.write(text) def _write(self, f, e): - f.write('<' + unicode_type(e.tag)) + f.write('<' + str(e.tag)) attributes = e.items() attributes.sort() diff --git a/src/calibre/ebooks/lrf/pylrs/pylrf.py b/src/calibre/ebooks/lrf/pylrs/pylrf.py index 3a9c73bb14..91889b14ae 100644 --- a/src/calibre/ebooks/lrf/pylrs/pylrf.py +++ b/src/calibre/ebooks/lrf/pylrs/pylrf.py @@ -12,7 +12,7 @@ import os from .pylrfopt import tagListOptimizer -from polyglot.builtins import iteritems, string_or_bytes, unicode_type +from polyglot.builtins import iteritems, string_or_bytes PYLRF_VERSION = "1.0" @@ -85,7 +85,7 @@ def writeWord(f, word): if int(word) > 65535: raise LrfError('Cannot encode a number greater than 65535 in a word.') if int(word) < 0: - raise LrfError('Cannot encode a number < 0 in a word: '+unicode_type(word)) + raise LrfError('Cannot encode a number < 0 in a word: '+str(word)) f.write(struct.pack("= 4000 or int(num) != num: - return unicode_type(num) + return str(num) result = [] for d, r in coding: while num >= d: @@ -222,7 +222,7 @@ def fmt_sidx(i, fmt='%.2f', use_roman=False): try: i = float(i) except Exception: - return unicode_type(i) + return str(i) if int(i) == float(i): return roman(int(i)) if use_roman else '%d'%int(i) return fmt%i @@ -266,7 +266,7 @@ def __init__(self, href_or_path, basedir=os.getcwd(), is_path=True): self._href = href_or_path else: pc = url[2] - if isinstance(pc, unicode_type): + if isinstance(pc, str): pc = pc.encode('utf-8') pc = unquote(pc).decode('utf-8') self.path = os.path.abspath(os.path.join(basedir, pc.replace('/', os.sep))) @@ -287,7 +287,7 @@ def href(self, basedir=None): basedir = os.getcwd() if self.path is None: return self._href - f = self.fragment.encode('utf-8') if isinstance(self.fragment, unicode_type) else self.fragment + f = self.fragment.encode('utf-8') if isinstance(self.fragment, str) else self.fragment frag = '#'+as_unicode(quote(f)) if self.fragment else '' if self.path == basedir: return ''+frag @@ -295,7 +295,7 @@ def href(self, basedir=None): rpath = relpath(self.path, basedir) except OSError: # On windows path and basedir could be on different drives rpath = self.path - if isinstance(rpath, unicode_type): + if isinstance(rpath, str): rpath = rpath.encode('utf-8') return as_unicode(quote(rpath.replace(os.sep, '/')))+frag @@ -332,7 +332,7 @@ def __str__(self): return '[%s]'%', '.join(resources) def __repr__(self): - return unicode_type(self) + return str(self) def append(self, resource): if not isinstance(resource, Resource): diff --git a/src/calibre/ebooks/metadata/archive.py b/src/calibre/ebooks/metadata/archive.py index 425a8fb3da..5c75ab11f1 100644 --- a/src/calibre/ebooks/metadata/archive.py +++ b/src/calibre/ebooks/metadata/archive.py @@ -11,7 +11,6 @@ from calibre.customize import FileTypePlugin from calibre.utils.localization import canonicalize_lang -from polyglot.builtins import unicode_type def is_comic(list_of_names): @@ -170,7 +169,7 @@ def get_comic_book_info(d, mi, series_index='volume'): from datetime import date try: dt = date(puby, 6 if pubm is None else pubm, 15) - dt = parse_only_date(unicode_type(dt)) + dt = parse_only_date(str(dt)) mi.pubdate = dt except Exception: pass diff --git a/src/calibre/ebooks/metadata/author_mapper.py b/src/calibre/ebooks/metadata/author_mapper.py index 2b81183a74..efffaa6fc4 100644 --- a/src/calibre/ebooks/metadata/author_mapper.py +++ b/src/calibre/ebooks/metadata/author_mapper.py @@ -7,7 +7,6 @@ from collections import deque from calibre.utils.icu import capitalize, lower, upper -from polyglot.builtins import unicode_type def cap_author_token(token): @@ -161,9 +160,9 @@ def rule(action, query, replace=None, match_type='one_of'): def run(rules, authors, expected): if isinstance(rules, dict): rules = [rules] - if isinstance(authors, unicode_type): + if isinstance(authors, str): authors = [x.strip() for x in authors.split('&')] - if isinstance(expected, unicode_type): + if isinstance(expected, str): expected = [x.strip() for x in expected.split('&')] ans = map_authors(authors, compile_rules(rules)) self.assertEqual(ans, expected) diff --git a/src/calibre/ebooks/metadata/book/base.py b/src/calibre/ebooks/metadata/book/base.py index 11b959092a..b547d68dc5 100644 --- a/src/calibre/ebooks/metadata/book/base.py +++ b/src/calibre/ebooks/metadata/book/base.py @@ -15,7 +15,7 @@ TOP_LEVEL_IDENTIFIERS, ALL_METADATA_FIELDS) from calibre.library.field_metadata import FieldMetadata from calibre.utils.icu import sort_key -from polyglot.builtins import iteritems, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, string_or_bytes # Special sets used to optimize the performance of getting and setting # attributes on Metadata objects @@ -28,7 +28,7 @@ def human_readable(size, precision=2): ans = size/(1024*1024) if ans < 0.1: return '<0.1MB' - return ('%.'+unicode_type(precision)+'f'+ 'MB') % ans + return ('%.'+str(precision)+'f'+ 'MB') % ans NULL_VALUES = { @@ -626,14 +626,14 @@ def format_authors(self): return authors_to_string(self.authors) def format_tags(self): - return ', '.join([unicode_type(t) for t in sorted(self.tags, key=sort_key)]) + return ', '.join([str(t) for t in sorted(self.tags, key=sort_key)]) def format_rating(self, v=None, divide_by=1): if v is None: if self.rating is not None: - return unicode_type(self.rating/divide_by) + return str(self.rating/divide_by) return 'None' - return unicode_type(v/divide_by) + return str(v/divide_by) def format_field(self, key, series_with_index=True): ''' @@ -657,15 +657,15 @@ def format_field_extended(self, key, series_with_index=True): if cmeta and cmeta['datatype'] == 'series': if self.get(tkey): res = self.get_extra(tkey) - return (unicode_type(cmeta['name']+'_index'), + return (str(cmeta['name']+'_index'), self.format_series_index(res), res, cmeta) else: - return (unicode_type(cmeta['name']+'_index'), '', '', cmeta) + return (str(cmeta['name']+'_index'), '', '', cmeta) if key in self.custom_field_keys(): res = self.get(key, None) # get evaluates all necessary composites cmeta = self.get_user_metadata(key, make_copy=False) - name = unicode_type(cmeta['name']) + name = str(cmeta['name']) if res is None or res == '': # can't check "not res" because of numeric fields return (name, res, None, None) orig_res = res @@ -688,7 +688,7 @@ def format_field_extended(self, key, series_with_index=True): res = fmt.format(res) except: pass - return (name, unicode_type(res), orig_res, cmeta) + return (name, str(res), orig_res, cmeta) # convert top-level ids into their value if key in TOP_LEVEL_IDENTIFIERS: @@ -702,11 +702,11 @@ def format_field_extended(self, key, series_with_index=True): if fmkey in field_metadata and field_metadata[fmkey]['kind'] == 'field': res = self.get(key, None) fmeta = field_metadata[fmkey] - name = unicode_type(fmeta['name']) + name = str(fmeta['name']) if res is None or res == '': return (name, res, None, None) orig_res = res - name = unicode_type(fmeta['name']) + name = str(fmeta['name']) datatype = fmeta['datatype'] if key == 'authors': res = authors_to_string(res) @@ -724,7 +724,7 @@ def format_field_extended(self, key, series_with_index=True): res = '%.2g'%(res/2) elif key == 'size': res = human_readable(res) - return (name, unicode_type(res), orig_res, fmeta) + return (name, str(res), orig_res, fmeta) return (None, None, None, None) @@ -738,7 +738,7 @@ def __unicode__representation__(self): ans = [] def fmt(x, y): - ans.append('%-20s: %s'%(unicode_type(x), unicode_type(y))) + ans.append('%-20s: %s'%(str(x), str(y))) fmt('Title', self.title) if self.title_sort: @@ -752,7 +752,7 @@ def fmt(x, y): if getattr(self, 'book_producer', False): fmt('Book Producer', self.book_producer) if self.tags: - fmt('Tags', ', '.join([unicode_type(t) for t in self.tags])) + fmt('Tags', ', '.join([str(t) for t in self.tags])) if self.series: fmt('Series', self.series + ' #%s'%self.format_series_index()) if not self.is_null('languages'): @@ -765,7 +765,7 @@ def fmt(x, y): if self.pubdate is not None: fmt('Published', isoformat(self.pubdate)) if self.rights is not None: - fmt('Rights', unicode_type(self.rights)) + fmt('Rights', str(self.rights)) if self.identifiers: fmt('Identifiers', ', '.join(['%s:%s'%(k, v) for k, v in iteritems(self.identifiers)])) @@ -776,7 +776,7 @@ def fmt(x, y): val = self.get(key, None) if val: (name, val) = self.format_field(key) - fmt(name, unicode_type(val)) + fmt(name, str(val)) return '\n'.join(ans) def to_html(self): @@ -785,22 +785,22 @@ def to_html(self): ''' from calibre.ebooks.metadata import authors_to_string from calibre.utils.date import isoformat - ans = [(_('Title'), unicode_type(self.title))] + ans = [(_('Title'), str(self.title))] ans += [(_('Author(s)'), (authors_to_string(self.authors) if self.authors else _('Unknown')))] - ans += [(_('Publisher'), unicode_type(self.publisher))] - ans += [(_('Producer'), unicode_type(self.book_producer))] - ans += [(_('Comments'), unicode_type(self.comments))] - ans += [('ISBN', unicode_type(self.isbn))] - ans += [(_('Tags'), ', '.join([unicode_type(t) for t in self.tags]))] + ans += [(_('Publisher'), str(self.publisher))] + ans += [(_('Producer'), str(self.book_producer))] + ans += [(_('Comments'), str(self.comments))] + ans += [('ISBN', str(self.isbn))] + ans += [(_('Tags'), ', '.join([str(t) for t in self.tags]))] if self.series: - ans += [(ngettext('Series', 'Series', 1), unicode_type(self.series) + ' #%s'%self.format_series_index())] + ans += [(ngettext('Series', 'Series', 1), str(self.series) + ' #%s'%self.format_series_index())] ans += [(_('Languages'), ', '.join(self.languages))] if self.timestamp is not None: - ans += [(_('Timestamp'), unicode_type(isoformat(self.timestamp, as_utc=False, sep=' ')))] + ans += [(_('Timestamp'), str(isoformat(self.timestamp, as_utc=False, sep=' ')))] if self.pubdate is not None: - ans += [(_('Published'), unicode_type(isoformat(self.pubdate, as_utc=False, sep=' ')))] + ans += [(_('Published'), str(isoformat(self.pubdate, as_utc=False, sep=' ')))] if self.rights is not None: - ans += [(_('Rights'), unicode_type(self.rights))] + ans += [(_('Rights'), str(self.rights))] for key in self.custom_field_keys(): val = self.get(key, None) if val: diff --git a/src/calibre/ebooks/metadata/book/serialize.py b/src/calibre/ebooks/metadata/book/serialize.py index 48f54d9fa5..1ee1348d08 100644 --- a/src/calibre/ebooks/metadata/book/serialize.py +++ b/src/calibre/ebooks/metadata/book/serialize.py @@ -7,12 +7,12 @@ from calibre.ebooks.metadata.book import SERIALIZABLE_FIELDS from calibre.ebooks.metadata.book.base import Metadata from calibre.utils.imghdr import what -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.binary import as_base64_unicode def ensure_unicode(obj, enc=preferred_encoding): - if isinstance(obj, unicode_type): + if isinstance(obj, str): return obj if isinstance(obj, bytes): return obj.decode(enc, 'replace') diff --git a/src/calibre/ebooks/metadata/cli.py b/src/calibre/ebooks/metadata/cli.py index feb058317e..ae16e9366b 100644 --- a/src/calibre/ebooks/metadata/cli.py +++ b/src/calibre/ebooks/metadata/cli.py @@ -17,7 +17,7 @@ from calibre.ebooks.lrf.meta import LRFMetaFile from calibre import prints from calibre.utils.date import parse_date -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems USAGE=_('%prog ebook_file [options]\n') + \ _(''' @@ -183,7 +183,7 @@ def main(args=sys.argv): mi = get_metadata(stream, stream_type, force_read_metadata=True) if trying_to_set: prints(_('Original metadata')+'::') - metadata = unicode_type(mi) + metadata = str(mi) if trying_to_set: metadata = '\t'+'\n\t'.join(metadata.split('\n')) prints(metadata) @@ -200,7 +200,7 @@ def main(args=sys.argv): lrf.book_id = opts.lrf_bookid mi = get_metadata(stream, stream_type, force_read_metadata=True) prints('\n' + _('Changed metadata') + '::') - metadata = unicode_type(mi) + metadata = str(mi) metadata = '\t'+'\n\t'.join(metadata.split('\n')) prints(metadata) if lrf is not None: diff --git a/src/calibre/ebooks/metadata/fb2.py b/src/calibre/ebooks/metadata/fb2.py index c557beb464..ef3fb65fc7 100644 --- a/src/calibre/ebooks/metadata/fb2.py +++ b/src/calibre/ebooks/metadata/fb2.py @@ -21,7 +21,6 @@ from calibre import guess_type, guess_all_extensions, prints, force_unicode from calibre.ebooks.metadata import MetaInformation, check_isbn from calibre.ebooks.chardet import xml_to_unicode -from polyglot.builtins import unicode_type from polyglot.binary import as_base64_unicode @@ -117,7 +116,7 @@ def get_metadata(stream): # fallback for book_title if book_title: - book_title = unicode_type(book_title) + book_title = str(book_title) else: book_title = force_unicode(os.path.splitext( os.path.basename(getattr(stream, 'name', @@ -254,7 +253,7 @@ def _parse_tags(root, mi, ctx): # -- i18n Translations-- ? tags = ctx.XPath('//fb:%s/fb:genre/text()' % genre_sec)(root) if tags: - mi.tags = list(map(unicode_type, tags)) + mi.tags = list(map(str, tags)) break @@ -306,7 +305,7 @@ def _parse_pubdate(root, mi, ctx): year = ctx.XPath('number(//fb:publish-info/fb:year/text())')(root) if float.is_integer(year): # only year is available, so use 2nd of June - mi.pubdate = parse_only_date(unicode_type(int(year))) + mi.pubdate = parse_only_date(str(int(year))) def _parse_language(root, mi, ctx): diff --git a/src/calibre/ebooks/metadata/imp.py b/src/calibre/ebooks/metadata/imp.py index d026168b5d..b65a09fc07 100644 --- a/src/calibre/ebooks/metadata/imp.py +++ b/src/calibre/ebooks/metadata/imp.py @@ -7,7 +7,6 @@ import sys from calibre.ebooks.metadata import MetaInformation, string_to_authors -from polyglot.builtins import unicode_type MAGIC = (b'\x00\x01BOOKDOUG', b'\x00\x02BOOKDOUG') @@ -45,6 +44,6 @@ def cString(skip=0): if category: mi.category = category except Exception as err: - msg = 'Couldn\'t read metadata from imp: %s with error %s'%(mi.title, unicode_type(err)) + msg = 'Couldn\'t read metadata from imp: %s with error %s'%(mi.title, str(err)) print(msg.encode('utf8'), file=sys.stderr) return mi diff --git a/src/calibre/ebooks/metadata/kdl.py b/src/calibre/ebooks/metadata/kdl.py index 80ccd398c2..526455ab15 100644 --- a/src/calibre/ebooks/metadata/kdl.py +++ b/src/calibre/ebooks/metadata/kdl.py @@ -14,7 +14,7 @@ from calibre import browser from calibre.ebooks.BeautifulSoup import BeautifulSoup from calibre.ebooks.chardet import xml_to_unicode -from polyglot.builtins import codepoint_to_chr, unicode_type +from polyglot.builtins import codepoint_to_chr from polyglot.urllib import parse_qs, quote_plus URL = \ @@ -30,7 +30,7 @@ def get_series(title, authors, timeout=60): title = re.sub(r'^(A|The|An)\s+', '', title).strip() if not title: return mi - if isinstance(title, unicode_type): + if isinstance(title, str): title = title.encode('utf-8') title = quote_plus(title) @@ -75,7 +75,7 @@ def get_series(title, authors, timeout=60): mi.series = series ns = ss.nextSibling if ns.contents: - raw = unicode_type(ns.contents[0]) + raw = str(ns.contents[0]) raw = raw.partition('.')[0].strip() try: mi.series_index = int(raw) diff --git a/src/calibre/ebooks/metadata/kfx.py b/src/calibre/ebooks/metadata/kfx.py index 38c33c08a4..c156e25dd7 100644 --- a/src/calibre/ebooks/metadata/kfx.py +++ b/src/calibre/ebooks/metadata/kfx.py @@ -16,7 +16,6 @@ from calibre.utils.date import parse_only_date from calibre.utils.localization import canonicalize_lang from calibre.utils.imghdr import identify -from polyglot.builtins import unicode_type from polyglot.binary import as_base64_bytes, from_base64_bytes @@ -364,4 +363,4 @@ def fix_author(x): from calibre import prints with open(sys.argv[-1], 'rb') as f: mi = read_metadata_kfx(f) - prints(unicode_type(mi)) + prints(str(mi)) diff --git a/src/calibre/ebooks/metadata/meta.py b/src/calibre/ebooks/metadata/meta.py index b6433bad68..08eb2ce25a 100644 --- a/src/calibre/ebooks/metadata/meta.py +++ b/src/calibre/ebooks/metadata/meta.py @@ -11,7 +11,6 @@ from calibre import isbytestring from calibre.customize.ui import get_file_type_metadata, set_file_type_metadata from calibre.ebooks.metadata import MetaInformation, string_to_authors -from polyglot.builtins import unicode_type # The priorities for loading metadata from different file types # Higher values should be used to update metadata from lower values @@ -242,7 +241,7 @@ def forked_read_metadata(original_path, tdir): f.seek(0, 2) sz = f.tell() with lopen(os.path.join(tdir, 'size.txt'), 'wb') as s: - s.write(unicode_type(sz).encode('ascii')) + s.write(str(sz).encode('ascii')) f.seek(0) mi = get_metadata(f, fmt) if mi.cover_data and mi.cover_data[1]: diff --git a/src/calibre/ebooks/metadata/mobi.py b/src/calibre/ebooks/metadata/mobi.py index f6d0b89d9c..3a5c750045 100644 --- a/src/calibre/ebooks/metadata/mobi.py +++ b/src/calibre/ebooks/metadata/mobi.py @@ -15,7 +15,7 @@ from calibre.utils.date import now as nowf from calibre.utils.imghdr import what from calibre.utils.localization import canonicalize_lang, lang_as_iso639_1 -from polyglot.builtins import codepoint_to_chr, unicode_type +from polyglot.builtins import codepoint_to_chr ''' @@ -223,7 +223,7 @@ def patchSection(self, section, new): def create_exth(self, new_title=None, exth=None): # Add an EXTH block to record 0, rewrite the stream - if isinstance(new_title, unicode_type): + if isinstance(new_title, str): new_title = new_title.encode(self.codec, 'replace') # Fetch the existing title @@ -381,9 +381,9 @@ def update_exth_record(rec): update_exth_record((501, b'PDOC')) if mi.pubdate: - update_exth_record((106, unicode_type(mi.pubdate).encode(self.codec, 'replace'))) + update_exth_record((106, str(mi.pubdate).encode(self.codec, 'replace'))) elif mi.timestamp: - update_exth_record((106, unicode_type(mi.timestamp).encode(self.codec, 'replace'))) + update_exth_record((106, str(mi.timestamp).encode(self.codec, 'replace'))) elif self.timestamp: update_exth_record((106, self.timestamp)) else: @@ -398,7 +398,7 @@ def update_exth_record(rec): self.original_exth_records.get(501, None) == b'EBOK' and not added_501 and not share_not_sync): from uuid import uuid4 - update_exth_record((113, unicode_type(uuid4()).encode(self.codec))) + update_exth_record((113, str(uuid4()).encode(self.codec))) if asin is not None: update_exth_record((113, asin.encode(self.codec))) diff --git a/src/calibre/ebooks/metadata/opf2.py b/src/calibre/ebooks/metadata/opf2.py index 103d6ae9f6..8786468b13 100644 --- a/src/calibre/ebooks/metadata/opf2.py +++ b/src/calibre/ebooks/metadata/opf2.py @@ -24,7 +24,7 @@ from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars from calibre.utils.config import tweaks from calibre.utils.xml_parse import safe_xml_fromstring -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.urllib import unquote, urlparse pretty_print_opf = False @@ -83,7 +83,7 @@ def __init__(self, href_or_path, basedir=os.getcwd(), is_path=True): self._href = href_or_path else: pc = url[2] - if isinstance(pc, unicode_type): + if isinstance(pc, str): pc = pc.encode('utf-8') pc = pc.decode('utf-8') self.path = os.path.abspath(os.path.join(basedir, pc.replace('/', os.sep))) @@ -151,7 +151,7 @@ def __str__(self): __unicode__ = __str__ def __repr__(self): - return unicode_type(self) + return str(self) def append(self, resource): if not isinstance(resource, Resource): @@ -208,7 +208,7 @@ def __unicode__representation__(self): __str__ = __unicode__representation__ def __repr__(self): - return unicode_type(self) + return str(self) def __getitem__(self, index): if index == 0: @@ -411,7 +411,7 @@ def set_cover(self, path): class MetadataField: def __init__(self, name, is_dc=True, formatter=None, none_is=None, - renderer=lambda x: unicode_type(x)): + renderer=lambda x: str(x)): self.name = name self.is_dc = is_dc self.formatter = formatter @@ -811,7 +811,7 @@ def iterguide(self): def unquote_urls(self): def get_href(item): raw = unquote(item.get('href', '')) - if not isinstance(raw, unicode_type): + if not isinstance(raw, str): raw = raw.decode('utf-8') return raw for item in self.itermanifest(): @@ -840,7 +840,7 @@ def title(self, val): titles = () if val: title = titles[0] if titles else self.create_metadata_element('title') - title.text = re.sub(r'\s+', ' ', unicode_type(val)) + title.text = re.sub(r'\s+', ' ', str(val)) @property def authors(self): @@ -883,7 +883,7 @@ def author_sort(self, val): for key in matches[0].attrib: if key.endswith('file-as'): matches[0].attrib.pop(key) - matches[0].set('{%s}file-as'%self.NAMESPACES['opf'], unicode_type(val)) + matches[0].set('{%s}file-as'%self.NAMESPACES['opf'], str(val)) @property def tags(self): @@ -900,7 +900,7 @@ def tags(self, val): tag.getparent().remove(tag) for tag in val: elem = self.create_metadata_element('subject') - self.set_text(elem, unicode_type(tag)) + self.set_text(elem, str(tag)) @property def pubdate(self): @@ -956,7 +956,7 @@ def isbn(self, val): xid = x.get('id', None) is_package_identifier = uuid_id is not None and uuid_id == xid if is_package_identifier: - self.set_text(x, unicode_type(uuid.uuid4())) + self.set_text(x, str(uuid.uuid4())) for attr in x.attrib: if attr.endswith('scheme'): x.attrib[attr] = 'uuid' @@ -967,7 +967,7 @@ def isbn(self, val): attrib = {'{%s}scheme'%self.NAMESPACES['opf']: 'ISBN'} matches = [self.create_metadata_element('identifier', attrib=attrib)] - self.set_text(matches[0], unicode_type(val)) + self.set_text(matches[0], str(val)) def get_identifiers(self): identifiers = {} @@ -1030,7 +1030,7 @@ def set_identifiers(self, identifiers): for typ, val in iteritems(identifiers): attrib = {'{%s}scheme'%self.NAMESPACES['opf']: typ.upper()} self.set_text(self.create_metadata_element( - 'identifier', attrib=attrib), unicode_type(val)) + 'identifier', attrib=attrib), str(val)) @property def application_id(self): @@ -1053,7 +1053,7 @@ def application_id(self, val): if uuid_id and uuid_id in removed_ids: attrib['id'] = uuid_id self.set_text(self.create_metadata_element( - 'identifier', attrib=attrib), unicode_type(val)) + 'identifier', attrib=attrib), str(val)) @property def uuid(self): @@ -1067,7 +1067,7 @@ def uuid(self, val): attrib = {'{%s}scheme'%self.NAMESPACES['opf']: 'uuid'} matches = [self.create_metadata_element('identifier', attrib=attrib)] - self.set_text(matches[0], unicode_type(val)) + self.set_text(matches[0], str(val)) @property def language(self): @@ -1098,7 +1098,7 @@ def languages(self, val): for lang in val: l = self.create_metadata_element('language') - self.set_text(l, unicode_type(lang)) + self.set_text(l, str(lang)) @property def raw_languages(self): @@ -1118,7 +1118,7 @@ def book_producer(self, val): if not matches: matches = [self.create_metadata_element('contributor')] matches[0].set('{%s}role'%self.NAMESPACES['opf'], 'bkp') - self.set_text(matches[0], unicode_type(val)) + self.set_text(matches[0], str(val)) def identifier_iter(self): for item in self.identifier_path(self.metadata): @@ -1381,7 +1381,7 @@ def __init__(self, base_path, other): self.page_progression_direction = None self.primary_writing_mode = None if self.application_id is None: - self.application_id = unicode_type(uuid.uuid4()) + self.application_id = str(uuid.uuid4()) if not isinstance(self.toc, TOC): self.toc = None if not self.authors: @@ -1505,7 +1505,7 @@ def CAL_ELEM(name, content): a(DC_ELEM('contributor', '%s (%s) [%s]'%(__appname__, __version__, 'https://calibre-ebook.com'), opf_attrs={'role':'bkp', 'file-as':__appname__})) - a(DC_ELEM('identifier', unicode_type(self.application_id), + a(DC_ELEM('identifier', str(self.application_id), opf_attrs={'scheme':__appname__}, dc_attrs={'id':__appname__+'_id'})) if getattr(self, 'pubdate', None) is not None: @@ -1533,7 +1533,7 @@ def CAL_ELEM(name, content): if self.title_sort: a(CAL_ELEM('calibre:title_sort', self.title_sort)) if self.rating is not None: - a(CAL_ELEM('calibre:rating', unicode_type(self.rating))) + a(CAL_ELEM('calibre:rating', str(self.rating))) if self.timestamp is not None: a(CAL_ELEM('calibre:timestamp', self.timestamp.isoformat())) if self.publication_type is not None: @@ -1550,7 +1550,7 @@ def CAL_ELEM(name, content): href = ref.href() if isinstance(href, bytes): href = href.decode('utf-8') - item = E.item(id=unicode_type(ref.id), href=href) + item = E.item(id=str(ref.id), href=href) item.set('media-type', ref.mime_type) manifest.append(item) spine = E.spine() @@ -1601,10 +1601,10 @@ def metadata_to_opf(mi, as_string=True, default_lang=None): from calibre.ebooks.oeb.base import OPF, DC if not mi.application_id: - mi.application_id = unicode_type(uuid.uuid4()) + mi.application_id = str(uuid.uuid4()) if not mi.uuid: - mi.uuid = unicode_type(uuid.uuid4()) + mi.uuid = str(uuid.uuid4()) if not mi.book_producer: mi.book_producer = __appname__ + ' (%s) '%__version__ + \ @@ -1685,7 +1685,7 @@ def factory(tag, text=None, sort=None, role=None, scheme=None, name=None, if mi.series_index is not None: meta('series_index', mi.format_series_index()) if mi.rating is not None: - meta('rating', unicode_type(mi.rating)) + meta('rating', str(mi.rating)) if hasattr(mi.timestamp, 'isoformat'): meta('timestamp', isoformat(mi.timestamp)) if mi.publication_type: @@ -1703,7 +1703,7 @@ def factory(tag, text=None, sort=None, role=None, scheme=None, name=None, metadata[-1].tail = '\n' +(' '*4) if mi.cover: - if not isinstance(mi.cover, unicode_type): + if not isinstance(mi.cover, str): mi.cover = mi.cover.decode(filesystem_encoding) guide.text = '\n'+(' '*8) r = guide.makeelement(OPF('reference'), diff --git a/src/calibre/ebooks/metadata/pdf.py b/src/calibre/ebooks/metadata/pdf.py index 8e4733bd7c..929a36beb7 100644 --- a/src/calibre/ebooks/metadata/pdf.py +++ b/src/calibre/ebooks/metadata/pdf.py @@ -13,7 +13,7 @@ from calibre.ebooks.metadata import ( MetaInformation, string_to_authors, check_isbn, check_doi) from calibre.utils.ipc.simple_worker import fork_job, WorkerError -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def get_tools(): @@ -90,8 +90,8 @@ def page_images(pdfpath, outputdir='.', first=1, last=1, image_format='jpeg', pr args['creationflags'] = subprocess.HIGH_PRIORITY_CLASS | subprocess.CREATE_NO_WINDOW try: subprocess.check_call([ - pdftoppm, '-cropbox', '-' + image_format, '-f', unicode_type(first), - '-l', unicode_type(last), pdfpath, os.path.join(outputdir, prefix) + pdftoppm, '-cropbox', '-' + image_format, '-f', str(first), + '-l', str(last), pdfpath, os.path.join(outputdir, prefix) ], **args) except subprocess.CalledProcessError as e: raise ValueError('Failed to render PDF, pdftoppm errorcode: %s'%e.returncode) diff --git a/src/calibre/ebooks/metadata/rb.py b/src/calibre/ebooks/metadata/rb.py index 9869f2cd30..420d186bc6 100644 --- a/src/calibre/ebooks/metadata/rb.py +++ b/src/calibre/ebooks/metadata/rb.py @@ -8,7 +8,6 @@ from calibre import prints from calibre.ebooks.metadata import MetaInformation, string_to_authors -from polyglot.builtins import unicode_type MAGIC = b'\xb0\x0c\xb0\x0c\x02\x00NUVO\x00\x00\x00\x00' @@ -49,7 +48,7 @@ def get_metadata(stream): elif key.strip() == 'AUTHOR': mi.authors = string_to_authors(value) except Exception as err: - msg = 'Couldn\'t read metadata from rb: %s with error %s'%(mi.title, unicode_type(err)) + msg = 'Couldn\'t read metadata from rb: %s with error %s'%(mi.title, str(err)) prints(msg, file=sys.stderr) raise return mi diff --git a/src/calibre/ebooks/metadata/rtf.py b/src/calibre/ebooks/metadata/rtf.py index b8d621aaba..7c24f2d070 100644 --- a/src/calibre/ebooks/metadata/rtf.py +++ b/src/calibre/ebooks/metadata/rtf.py @@ -11,7 +11,7 @@ from calibre import force_unicode from calibre.ebooks.metadata import MetaInformation -from polyglot.builtins import codepoint_to_chr, string_or_bytes, unicode_type, int_to_byte +from polyglot.builtins import codepoint_to_chr, string_or_bytes, int_to_byte title_pat = re.compile(br'\{\\info.*?\{\\title(.*?)(? 1: istates[-2].list_num += 1 - para.attrib['value'] = unicode_type(istates[-2].list_num) + para.attrib['value'] = str(istates[-2].list_num) elif tag in NESTABLE_TAGS and istate.rendered: para = wrapper = bstate.nested[-1] elif not self.opts.mobi_ignore_margins and left > 0 and indent >= 0: @@ -240,7 +240,7 @@ def mobimlize_content(self, tag, text, bstate, istates): while vspace > 0: wrapper.addprevious(etree.Element(XHTML('br'))) vspace -= 1 - if istate.halign != 'auto' and isinstance(istate.halign, (bytes, unicode_type)): + if istate.halign != 'auto' and isinstance(istate.halign, (bytes, str)): if isinstance(istate.halign, bytes): istate.halign = istate.halign.decode('utf-8') para.attrib['align'] = istate.halign @@ -297,7 +297,7 @@ def mobimlize_content(self, tag, text, bstate, istates): if fsize != 3: inline = etree.SubElement(inline, XHTML('font'), - size=unicode_type(fsize)) + size=str(fsize)) if istate.family == 'monospace': inline = etree.SubElement(inline, XHTML('tt')) if istate.italic: @@ -462,7 +462,7 @@ def mobimlize_elem(self, elem, stylizer, bstate, istates, (72/self.profile.dpi))) except: continue - result = unicode_type(pixs) + result = str(pixs) istate.attrib[prop] = result if 'width' not in istate.attrib or 'height' not in istate.attrib: href = self.current_spine_item.abshref(elem.attrib['src']) @@ -479,8 +479,8 @@ def mobimlize_elem(self, elem, stylizer, bstate, istates, else: if 'width' not in istate.attrib and 'height' not in \ istate.attrib: - istate.attrib['width'] = unicode_type(width) - istate.attrib['height'] = unicode_type(height) + istate.attrib['width'] = str(width) + istate.attrib['height'] = str(height) else: ar = width / height if 'width' not in istate.attrib: @@ -488,13 +488,13 @@ def mobimlize_elem(self, elem, stylizer, bstate, istates, width = int(istate.attrib['height'])*ar except: pass - istate.attrib['width'] = unicode_type(int(width)) + istate.attrib['width'] = str(int(width)) else: try: height = int(istate.attrib['width'])/ar except: pass - istate.attrib['height'] = unicode_type(int(height)) + istate.attrib['height'] = str(int(height)) item.unload_data_from_memory() elif tag == 'hr' and asfloat(style['width']) > 0 and style._get('width') not in {'100%', 'auto'}: raww = style._get('width') diff --git a/src/calibre/ebooks/mobi/reader/headers.py b/src/calibre/ebooks/mobi/reader/headers.py index e175830213..c24c0c2006 100644 --- a/src/calibre/ebooks/mobi/reader/headers.py +++ b/src/calibre/ebooks/mobi/reader/headers.py @@ -16,7 +16,6 @@ from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars from calibre.utils.localization import canonicalize_lang from calibre.utils.config_base import tweaks -from polyglot.builtins import unicode_type NULL_INDEX = 0xffffffff @@ -250,7 +249,7 @@ def __init__(self, raw, ident, user_encoding, log, try_extra_data_fix=False): self.exth_flag, = struct.unpack('>L', raw[0x80:0x84]) self.exth = None - if not isinstance(self.title, unicode_type): + if not isinstance(self.title, str): self.title = self.title.decode(self.codec, 'replace') if self.exth_flag & 0x40: try: diff --git a/src/calibre/ebooks/mobi/reader/mobi6.py b/src/calibre/ebooks/mobi/reader/mobi6.py index afa13812cb..9ea4376a91 100644 --- a/src/calibre/ebooks/mobi/reader/mobi6.py +++ b/src/calibre/ebooks/mobi/reader/mobi6.py @@ -28,7 +28,7 @@ from calibre.utils.img import AnimatedGIF, gif_data_to_png_data, save_cover_data_to from calibre.utils.imghdr import what from calibre.utils.logging import default_log -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class TopazError(ValueError): @@ -302,7 +302,7 @@ def extract_content(self, output_dir, parse_cache): pass def write_as_utf8(path, data): - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') with lopen(path, 'wb') as f: f.write(data) diff --git a/src/calibre/ebooks/mobi/reader/mobi8.py b/src/calibre/ebooks/mobi/reader/mobi8.py index c9e94bbd11..e480aadd43 100644 --- a/src/calibre/ebooks/mobi/reader/mobi8.py +++ b/src/calibre/ebooks/mobi/reader/mobi8.py @@ -23,7 +23,7 @@ from calibre.ebooks.mobi.utils import read_font_record from calibre.ebooks.oeb.parse_utils import parse_html from calibre.ebooks.oeb.base import XPath, XHTML, xml2text -from polyglot.builtins import unicode_type, as_unicode +from polyglot.builtins import as_unicode from polyglot.urllib import urldefrag Part = namedtuple('Part', @@ -225,7 +225,7 @@ def build_parts(self): self.parts.append(skeleton) if divcnt < 1: # Empty file - aidtext = unicode_type(uuid4()) + aidtext = str(uuid4()) filename = aidtext + '.html' self.partinfo.append(Part(skelnum, 'text', filename, skelpos, baseptr, aidtext)) diff --git a/src/calibre/ebooks/mobi/utils.py b/src/calibre/ebooks/mobi/utils.py index cf5f92aaf9..ab34265fa9 100644 --- a/src/calibre/ebooks/mobi/utils.py +++ b/src/calibre/ebooks/mobi/utils.py @@ -13,7 +13,7 @@ from calibre.utils.img import save_cover_data_to, scale_image, image_to_data, image_from_data, resize_image, png_data_to_gif_data from calibre.utils.imghdr import what from calibre.ebooks import normalize -from polyglot.builtins import unicode_type, as_bytes +from polyglot.builtins import as_bytes from tinycss.color3 import parse_color_string IMAGE_MAX_SIZE = 10 * 1024 * 1024 @@ -23,17 +23,17 @@ class PolyglotDict(dict): def __setitem__(self, key, val): - if isinstance(key, unicode_type): + if isinstance(key, str): key = key.encode('utf-8') dict.__setitem__(self, key, val) def __getitem__(self, key): - if isinstance(key, unicode_type): + if isinstance(key, str): key = key.encode('utf-8') return dict.__getitem__(self, key) def __contains__(self, key): - if isinstance(key, unicode_type): + if isinstance(key, str): key = key.encode('utf-8') return dict.__contains__(self, key) @@ -335,7 +335,7 @@ def utf8_text(text): ''' if text and text.strip(): text = text.strip() - if not isinstance(text, unicode_type): + if not isinstance(text, str): text = text.decode('utf-8', 'replace') text = normalize(text).encode('utf-8') else: @@ -638,7 +638,7 @@ def is_guide_ref_start(ref): def convert_color_for_font_tag(val): - rgba = parse_color_string(unicode_type(val or '')) + rgba = parse_color_string(str(val or '')) if rgba is None or rgba == 'currentColor': return str(val) clamp = lambda x: min(x, max(0, x), 1) diff --git a/src/calibre/ebooks/mobi/writer2/main.py b/src/calibre/ebooks/mobi/writer2/main.py index 4a2de0979e..c583d927da 100644 --- a/src/calibre/ebooks/mobi/writer2/main.py +++ b/src/calibre/ebooks/mobi/writer2/main.py @@ -18,7 +18,7 @@ from calibre.ebooks.mobi.utils import (encint, encode_trailing_data, align_block, detect_periodical, RECORD_SIZE, create_text_record) from calibre.ebooks.mobi.writer2.indexer import Indexer -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems # Disabled as I dont care about uncrossable breaks WRITE_UNCROSSABLE_BREAKS = False @@ -51,7 +51,7 @@ def __call__(self, oeb, path_or_stream): self.log = oeb.log pt = None if oeb.metadata.publication_type: - x = unicode_type(oeb.metadata.publication_type[0]).split(':') + x = str(oeb.metadata.publication_type[0]).split(':') if len(x) > 1: pt = x[1].lower() self.publication_type = pt @@ -238,7 +238,7 @@ def generate_record0(self): # MOBI header {{{ 0 # Unused )) # 0 - 15 (0x0 - 0xf) uid = random.randint(0, 0xffffffff) - title = normalize(unicode_type(metadata.title[0])).encode('utf-8') + title = normalize(str(metadata.title[0])).encode('utf-8') # 0x0 - 0x3 record0.write(b'MOBI') @@ -281,7 +281,7 @@ def generate_record0(self): # MOBI header {{{ # 0x4c - 0x4f : Language specifier record0.write(iana2mobi( - unicode_type(metadata.language[0]))) + str(metadata.language[0]))) # 0x50 - 0x57 : Input language and Output language record0.write(b'\0' * 8) @@ -458,7 +458,7 @@ def write_header(self): # PalmDB header {{{ ''' Write the PalmDB header ''' - title = ascii_filename(unicode_type(self.oeb.metadata.title[0])).replace( + title = ascii_filename(str(self.oeb.metadata.title[0])).replace( ' ', '_') if not isinstance(title, bytes): title = title.encode('ascii') diff --git a/src/calibre/ebooks/mobi/writer2/resources.py b/src/calibre/ebooks/mobi/writer2/resources.py index 36535d56f5..2bf2d22d96 100644 --- a/src/calibre/ebooks/mobi/writer2/resources.py +++ b/src/calibre/ebooks/mobi/writer2/resources.py @@ -17,7 +17,7 @@ from calibre.ebooks.oeb.base import OEB_RASTER_IMAGES from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.imghdr import what -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems PLACEHOLDER_GIF = b'GIF89a\x01\x00\x01\x00\xf0\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00!\xfe calibre-placeholder-gif-for-azw3\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;' # noqa @@ -90,7 +90,7 @@ def add_resources(self, add_fonts): self.image_indices.add(0) elif self.is_periodical: # Generate a default masthead - data = generate_masthead(unicode_type(self.oeb.metadata['title'][0])) + data = generate_masthead(str(self.oeb.metadata['title'][0])) self.records.append(data) self.used_image_indices.add(0) self.image_indices.add(0) @@ -98,8 +98,8 @@ def add_resources(self, add_fonts): cover_href = self.cover_offset = self.thumbnail_offset = None if (oeb.metadata.cover and - unicode_type(oeb.metadata.cover[0]) in oeb.manifest.ids): - cover_id = unicode_type(oeb.metadata.cover[0]) + str(oeb.metadata.cover[0]) in oeb.manifest.ids): + cover_id = str(oeb.metadata.cover[0]) item = oeb.manifest.ids[cover_id] cover_href = item.href diff --git a/src/calibre/ebooks/mobi/writer2/serializer.py b/src/calibre/ebooks/mobi/writer2/serializer.py index ad98becd9e..36ecdf1e9b 100644 --- a/src/calibre/ebooks/mobi/writer2/serializer.py +++ b/src/calibre/ebooks/mobi/writer2/serializer.py @@ -17,14 +17,14 @@ from calibre.ebooks.oeb.base import ( OEB_DOCS, XHTML, XHTML_NS, XML_NS, namespace, prefixname, urlnormalize ) -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes from polyglot.urllib import urldefrag class Buf(BytesIO): def write(self, x): - if isinstance(x, unicode_type): + if isinstance(x, str): x = x.encode('utf-8') BytesIO.write(self, x) @@ -230,7 +230,7 @@ def serialize_toc_level(tocref, href=None): buf.write(b'
') else: t = tocref.title - if isinstance(t, unicode_type): + if isinstance(t, str): t = t.encode('utf-8') buf.write(b'

' + t + b'

') @@ -250,7 +250,7 @@ def serialize_toc_level(tocref, href=None): buf.write(b'0000000000') buf.write(b' >') t = tocitem.title - if isinstance(t, unicode_type): + if isinstance(t, str): t = t.encode('utf-8') buf.write(t) buf.write(b'') @@ -368,7 +368,7 @@ def serialize_text(self, text, quot=False): text = text.replace(u'\u00AD', '') # Soft-hyphen if quot: text = text.replace('"', '"') - if isinstance(text, unicode_type): + if isinstance(text, str): text = unicodedata.normalize('NFC', text) self.buf.write(text.encode('utf-8')) diff --git a/src/calibre/ebooks/mobi/writer8/exth.py b/src/calibre/ebooks/mobi/writer8/exth.py index d8f62a90a5..1c3fc6d6a2 100644 --- a/src/calibre/ebooks/mobi/writer8/exth.py +++ b/src/calibre/ebooks/mobi/writer8/exth.py @@ -14,7 +14,7 @@ from calibre.ebooks.mobi.utils import (utf8_text, to_base) from calibre.utils.localization import lang_as_iso639_1 from calibre.ebooks.metadata import authors_to_sort_string -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems EXTH_CODES = { 'creator': 100, @@ -63,14 +63,14 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False, items = metadata[term] if term == 'creator': if prefer_author_sort: - creators = [authors_to_sort_string([unicode_type(c)]) for c in + creators = [authors_to_sort_string([str(c)]) for c in items] else: - creators = [unicode_type(c) for c in items] + creators = [str(c) for c in items] items = creators elif term == 'rights': try: - rights = utf8_text(unicode_type(metadata.rights[0])) + rights = utf8_text(str(metadata.rights[0])) except: rights = b'Unknown' exth.write(pack(b'>II', EXTH_CODES['rights'], len(rights) + 8)) @@ -79,7 +79,7 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False, continue for item in items: - data = unicode_type(item) + data = str(item) if term != 'description': data = COLLAPSE_RE.sub(' ', data) if term == 'identifier': @@ -103,14 +103,14 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False, from calibre.ebooks.oeb.base import OPF for x in metadata['identifier']: if (x.get(OPF('scheme'), None).lower() == 'uuid' or - unicode_type(x).startswith('urn:uuid:')): - uuid = unicode_type(x).split(':')[-1] + str(x).startswith('urn:uuid:')): + uuid = str(x).split(':')[-1] break if uuid is None: from uuid import uuid4 - uuid = unicode_type(uuid4()) + uuid = str(uuid4()) - if isinstance(uuid, unicode_type): + if isinstance(uuid, str): uuid = uuid.encode('utf-8') if not share_not_sync: exth.write(pack(b'>II', 113, len(uuid) + 8)) @@ -138,9 +138,9 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False, # Add a publication date entry if metadata['date']: - datestr = unicode_type(metadata['date'][0]) + datestr = str(metadata['date'][0]) elif metadata['timestamp']: - datestr = unicode_type(metadata['timestamp'][0]) + datestr = str(metadata['timestamp'][0]) if datestr is None: raise ValueError("missing date or timestamp") diff --git a/src/calibre/ebooks/mobi/writer8/index.py b/src/calibre/ebooks/mobi/writer8/index.py index 72af8b21d4..258c50b066 100644 --- a/src/calibre/ebooks/mobi/writer8/index.py +++ b/src/calibre/ebooks/mobi/writer8/index.py @@ -8,7 +8,6 @@ from collections import namedtuple from struct import pack from io import BytesIO -from polyglot.builtins import unicode_type from calibre.ebooks.mobi.utils import CNCX, encint, align_block from calibre.ebooks.mobi.writer8.header import Header @@ -143,7 +142,7 @@ def __call__(self): for i, (index_num, tags) in enumerate(self.entries): control_bytes = self.control_bytes[i] buf.seek(0), buf.truncate(0) - index_num = (index_num.encode('utf-8') if isinstance(index_num, unicode_type) else index_num) + index_num = (index_num.encode('utf-8') if isinstance(index_num, str) else index_num) raw = bytearray(index_num) raw.insert(0, len(index_num)) buf.write(bytes(raw)) diff --git a/src/calibre/ebooks/mobi/writer8/main.py b/src/calibre/ebooks/mobi/writer8/main.py index 78e552ad75..8657423929 100644 --- a/src/calibre/ebooks/mobi/writer8/main.py +++ b/src/calibre/ebooks/mobi/writer8/main.py @@ -30,7 +30,7 @@ from calibre.ebooks.mobi.writer8.mobi import KF8Book from calibre.ebooks.mobi.writer8.tbs import apply_trailing_byte_sequences from calibre.ebooks.mobi.writer8.toc import TOCAdder -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems XML_DOCS = OEB_DOCS | {SVG_MIME} @@ -333,7 +333,7 @@ def chunk_it_up(self): self.flows[0] = chunker.text def create_text_records(self): - self.flows = [x.encode('utf-8') if isinstance(x, unicode_type) else x for x + self.flows = [x.encode('utf-8') if isinstance(x, str) else x for x in self.flows] text = b''.join(self.flows) self.text_length = len(text) diff --git a/src/calibre/ebooks/mobi/writer8/mobi.py b/src/calibre/ebooks/mobi/writer8/mobi.py index 58e57ef6e8..3e98841d17 100644 --- a/src/calibre/ebooks/mobi/writer8/mobi.py +++ b/src/calibre/ebooks/mobi/writer8/mobi.py @@ -15,7 +15,6 @@ from calibre.ebooks.mobi.langcodes import iana2mobi from calibre.ebooks.mobi.writer8.exth import build_exth from calibre.utils.filenames import ascii_filename -from polyglot.builtins import unicode_type NULL_INDEX = 0xffffffff FLIS = b'FLIS\0\0\0\x08\0\x41\0\0\0\0\0\0\xff\xff\xff\xff\0\x01\0\x03\0\0\0\x03\0\0\0\x01'+ b'\xff'*4 @@ -282,14 +281,14 @@ def build_records(self, writer, for_joint): # Miscellaneous header fields self.compression = writer.compress self.book_type = 0x101 if writer.opts.mobi_periodical else 2 - self.full_title = utf8_text(unicode_type(metadata.title[0])) + self.full_title = utf8_text(str(metadata.title[0])) self.title_length = len(self.full_title) self.extra_data_flags = 0b1 if writer.has_tbs: self.extra_data_flags |= 0b10 self.uid = random.randint(0, 0xffffffff) - self.language_code = iana2mobi(unicode_type(metadata.language[0])) + self.language_code = iana2mobi(str(metadata.language[0])) self.exth_flags = 0b1010000 if writer.opts.mobi_periodical: self.exth_flags |= 0b1000 diff --git a/src/calibre/ebooks/mobi/writer8/skeleton.py b/src/calibre/ebooks/mobi/writer8/skeleton.py index 85c4d4fd8e..691485c49c 100644 --- a/src/calibre/ebooks/mobi/writer8/skeleton.py +++ b/src/calibre/ebooks/mobi/writer8/skeleton.py @@ -16,7 +16,7 @@ from calibre import my_unichr from calibre.ebooks.oeb.base import XHTML_NS, extract from calibre.ebooks.mobi.utils import to_base, PolyglotDict -from polyglot.builtins import iteritems, unicode_type, as_bytes +from polyglot.builtins import iteritems, as_bytes CHUNK_SIZE = 8192 @@ -69,7 +69,7 @@ def tostring(raw, **kwargs): xml_declaration = kwargs.pop('xml_declaration', False) encoding = kwargs.pop('encoding', 'UTF-8') - kwargs['encoding'] = unicode_type + kwargs['encoding'] = str kwargs['xml_declaration'] = False ans = etree.tostring(raw, **kwargs) if xml_declaration: diff --git a/src/calibre/ebooks/odt/input.py b/src/calibre/ebooks/odt/input.py index 2028dc0def..c31b2a985b 100644 --- a/src/calibre/ebooks/odt/input.py +++ b/src/calibre/ebooks/odt/input.py @@ -20,7 +20,7 @@ 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 unicode_type, string_or_bytes, as_bytes +from polyglot.builtins import string_or_bytes, as_bytes class Extract(ODF2XHTML): @@ -174,7 +174,7 @@ def filter_css(self, root, log): css = style.text if css: css, sel_map = self.do_filter_css(css) - if not isinstance(css, unicode_type): + if not isinstance(css, str): css = css.decode('utf-8', 'ignore') style.text = css for x in root.xpath('//*[@class]'): diff --git a/src/calibre/ebooks/oeb/base.py b/src/calibre/ebooks/oeb/base.py index dd1fd20d2d..2f7fbb7954 100644 --- a/src/calibre/ebooks/oeb/base.py +++ b/src/calibre/ebooks/oeb/base.py @@ -22,7 +22,7 @@ from calibre.ebooks.oeb.parse_utils import barename, XHTML_NS, namespace, XHTML, parse_html, NotHTML from calibre.utils.cleantext import clean_xml_chars from calibre.utils.short_uuid import uuid4 -from polyglot.builtins import iteritems, unicode_type, string_or_bytes, itervalues, codepoint_to_chr +from polyglot.builtins import iteritems, string_or_bytes, itervalues, codepoint_to_chr from polyglot.urllib import unquote as urlunquote, urldefrag, urljoin, urlparse, urlunparse from calibre.utils.icu import numeric_sort_key @@ -122,7 +122,7 @@ def as_string_type(pat, for_unicode): if isinstance(pat, bytes): pat = pat.decode('utf-8') else: - if isinstance(pat, unicode_type): + if isinstance(pat, str): pat = pat.encode('utf-8') return pat @@ -141,7 +141,7 @@ def self_closing_pat(for_unicode): def close_self_closing_tags(raw): - for_unicode = isinstance(raw, unicode_type) + for_unicode = isinstance(raw, str) repl = as_string_type(r'<\g\g>>', for_unicode) pat = self_closing_pat(for_unicode) return pat.sub(repl, raw) @@ -423,11 +423,11 @@ def serialize(data, media_type, pretty_print=False): # incorrectly by some browser based renderers ans = close_self_closing_tags(ans) return ans - if isinstance(data, unicode_type): + if isinstance(data, str): return data.encode('utf-8') if hasattr(data, 'cssText'): data = data.cssText - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') return data + b'\n' return bytes(data) @@ -569,7 +569,7 @@ def _unquote(self, path): # If it runs on a unicode object, it returns a double encoded unicode # string: unquote(u'%C3%A4') != unquote(b'%C3%A4').decode('utf-8') # and the latter is correct - if isinstance(path, unicode_type): + if isinstance(path, str): path = path.encode('utf-8') return urlunquote(path).decode('utf-8') @@ -913,9 +913,9 @@ class Item: """ def __init__(self, oeb, id, href, media_type, - fallback=None, loader=unicode_type, data=None): + fallback=None, loader=str, data=None): if href: - href = unicode_type(href) + href = str(href) self.oeb = oeb self.id = id self.href = self.path = urlnormalize(href) @@ -969,7 +969,7 @@ def _parse_txt(self, data): title = self.oeb.metadata.title if title: - title = unicode_type(title[0]) + title = str(title[0]) else: title = _('Unknown') @@ -1003,7 +1003,7 @@ def _fetch_css(self, path): self.oeb.logger.warn('CSS import of non-CSS file %r' % path) return (None, None) data = item.data.cssText - enc = None if isinstance(data, unicode_type) else 'utf-8' + enc = None if isinstance(data, str) else 'utf-8' return (enc, data) # }}} @@ -1087,11 +1087,11 @@ def unicode_representation(self): data = self.data if isinstance(data, etree._Element): return xml2text(data, pretty_print=self.oeb.pretty_print) - if isinstance(data, unicode_type): + if isinstance(data, str): return data if hasattr(data, 'cssText'): return css_text(data) - return unicode_type(data) + return str(data) @property def bytes_representation(self): @@ -1203,7 +1203,7 @@ def generate(self, id=None, href=None): base = id index = 1 while id in self.ids: - id = base + unicode_type(index) + id = base + str(index) index += 1 if href is not None: href = urlnormalize(href) @@ -1211,9 +1211,9 @@ def generate(self, id=None, href=None): index = 1 lhrefs = {x.lower() for x in self.hrefs} while href.lower() in lhrefs: - href = base + unicode_type(index) + ext + href = base + str(index) + ext index += 1 - return id, unicode_type(href) + return id, str(href) def __iter__(self): for item in self.items: @@ -1427,7 +1427,7 @@ def __init__(self, oeb): def add(self, type, title, href): """Add a new reference to the `Guide`.""" if href: - href = unicode_type(href) + href = str(href) ref = self.Reference(self.oeb, type, title, href) self.refs[type] = ref return ref @@ -1626,7 +1626,7 @@ def to_ncx(self, parent=None): po = node.play_order if po == 0: po = 1 - attrib = {'id': id, 'playOrder': unicode_type(po)} + attrib = {'id': id, 'playOrder': str(po)} if node.klass: attrib['class'] = node.klass point = element(parent, NCX('navPoint'), attrib=attrib) @@ -1697,7 +1697,7 @@ class Page: TYPES = {'front', 'normal', 'special'} def __init__(self, name, href, type='normal', klass=None, id=None): - self.name = unicode_type(name) + self.name = str(name) self.href = urlnormalize(href) self.type = type if type in self.TYPES else 'normal' self.id = id @@ -1734,7 +1734,7 @@ def to_ncx(self, parent=None): for page in self.pages: id = page.id or uuid_id() type = page.type - value = unicode_type(next(values[type])) + value = str(next(values[type])) attrib = {'id': id, 'value': value, 'type': type, 'playOrder': '0'} if page.klass: attrib['class'] = page.klass @@ -1827,7 +1827,7 @@ def generate(cls, opts): def translate(self, text): """Translate :param:`text` into the book's primary language.""" - lang = unicode_type(self.metadata.language[0]) + lang = str(self.metadata.language[0]) lang = lang.split('-', 1)[0].lower() return translate(lang, text) @@ -1835,7 +1835,7 @@ def decode(self, data): """Automatically decode :param:`data` into a `unicode` object.""" def fix_data(d): return d.replace('\r\n', '\n').replace('\r', '\n') - if isinstance(data, unicode_type): + if isinstance(data, str): return fix_data(data) bom_enc = None if data[:4] in (b'\0\0\xfe\xff', b'\xff\xfe\0\0'): @@ -1909,36 +1909,36 @@ def _update_playorder(self, ncx): for i, elem in enumerate(xpath(ncx, '//*[@playOrder and ./ncx:content[@src]]')): href = urlnormalize(selector(elem)[0]) order = playorder.get(href, i) - elem.attrib['playOrder'] = unicode_type(order) + elem.attrib['playOrder'] = str(order) return def _to_ncx(self): - lang = unicode_type(self.metadata.language[0]) + lang = str(self.metadata.language[0]) lang = lang.replace('_', '-') ncx = etree.Element(NCX('ncx'), attrib={'version': '2005-1', XML('lang'): lang}, nsmap={None: NCX_NS}) head = etree.SubElement(ncx, NCX('head')) etree.SubElement(head, NCX('meta'), - name='dtb:uid', content=unicode_type(self.uid)) + name='dtb:uid', content=str(self.uid)) etree.SubElement(head, NCX('meta'), - name='dtb:depth', content=unicode_type(self.toc.depth())) + name='dtb:depth', content=str(self.toc.depth())) generator = ''.join(['calibre (', __version__, ')']) etree.SubElement(head, NCX('meta'), name='dtb:generator', content=generator) etree.SubElement(head, NCX('meta'), - name='dtb:totalPageCount', content=unicode_type(len(self.pages))) + name='dtb:totalPageCount', content=str(len(self.pages))) maxpnum = etree.SubElement(head, NCX('meta'), name='dtb:maxPageNumber', content='0') title = etree.SubElement(ncx, NCX('docTitle')) text = etree.SubElement(title, NCX('text')) - text.text = unicode_type(self.metadata.title[0]) + text.text = str(self.metadata.title[0]) navmap = etree.SubElement(ncx, NCX('navMap')) self.toc.to_ncx(navmap) if len(self.pages) > 0: plist = self.pages.to_ncx(ncx) value = max(int(x) for x in xpath(plist, '//@value')) - maxpnum.attrib['content'] = unicode_type(value) + maxpnum.attrib['content'] = str(value) self._update_playorder(ncx) return ncx diff --git a/src/calibre/ebooks/oeb/iterator/bookmarks.py b/src/calibre/ebooks/oeb/iterator/bookmarks.py index e158cae23b..654c607071 100644 --- a/src/calibre/ebooks/oeb/iterator/bookmarks.py +++ b/src/calibre/ebooks/oeb/iterator/bookmarks.py @@ -10,7 +10,7 @@ from io import BytesIO from calibre.utils.zipfile import safe_replace -from polyglot.builtins import unicode_type, as_unicode +from polyglot.builtins import as_unicode BM_FIELD_SEP = u'*|!|?|*' BM_LEGACY_ESC = u'esc-text-%&*#%(){}ads19-end-esc' @@ -61,10 +61,10 @@ def serialize_bookmarks(self, bookmarks): else: pos = bm['pos'] if isinstance(pos, numbers.Number): - pos = unicode_type(pos) + pos = str(pos) else: pos = pos.replace(u'^', BM_LEGACY_ESC) - rec = BM_FIELD_SEP.join([bm['title'], unicode_type(bm['spine']), pos]) + rec = BM_FIELD_SEP.join([bm['title'], str(bm['spine']), pos]) dat.append(rec) return (u'\n'.join(dat) +u'\n') diff --git a/src/calibre/ebooks/oeb/iterator/spine.py b/src/calibre/ebooks/oeb/iterator/spine.py index dc615a5cbb..d04cfe7358 100644 --- a/src/calibre/ebooks/oeb/iterator/spine.py +++ b/src/calibre/ebooks/oeb/iterator/spine.py @@ -1,7 +1,6 @@ #!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai -from polyglot.builtins import unicode_type __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -44,7 +43,7 @@ def all_links(html): return ans -class SpineItem(unicode_type): +class SpineItem(str): def __new__(cls, path, mime_type=None, read_anchor_map=True, run_char_count=True, from_epub=False, read_links=True): diff --git a/src/calibre/ebooks/oeb/normalize_css.py b/src/calibre/ebooks/oeb/normalize_css.py index 9ed7efbd59..524bf5d623 100644 --- a/src/calibre/ebooks/oeb/normalize_css.py +++ b/src/calibre/ebooks/oeb/normalize_css.py @@ -12,7 +12,7 @@ from css_parser import profile as cssprofiles, CSSParser from tinycss.fonts3 import parse_font, serialize_font_family from calibre.ebooks.oeb.base import css_text -from polyglot.builtins import iteritems, string_or_bytes, unicode_type +from polyglot.builtins import iteritems, string_or_bytes DEFAULTS = {'azimuth': 'center', 'background-attachment': 'scroll', # {{{ 'background-color': 'transparent', 'background-image': 'none', @@ -393,7 +393,7 @@ def test_edge_condensation(self): tuple('0 0 0 0'.split()) : '0', }): for prefix in ('margin', 'padding'): - css = {'%s-%s' % (prefix, x) : unicode_type(y)+'pt' if isinstance(y, numbers.Number) else y + css = {'%s-%s' % (prefix, x) : str(y)+'pt' if isinstance(y, numbers.Number) else y for x, y in zip(('left', 'top', 'right', 'bottom'), s)} css = '; '.join(('%s:%s' % (k, v) for k, v in iteritems(css))) style = parseStyle(css) diff --git a/src/calibre/ebooks/oeb/parse_utils.py b/src/calibre/ebooks/oeb/parse_utils.py index 7667534160..f4557dbccb 100644 --- a/src/calibre/ebooks/oeb/parse_utils.py +++ b/src/calibre/ebooks/oeb/parse_utils.py @@ -14,7 +14,7 @@ from calibre.utils.xml_parse import safe_xml_fromstring from calibre.constants import filesystem_encoding from calibre.ebooks.chardet import xml_to_unicode, strip_encoding_declarations -from polyglot.builtins import iteritems, itervalues, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, itervalues, string_or_bytes RECOVER_PARSER = etree.XMLParser(recover=True, no_network=True, resolve_entities=False) XHTML_NS = 'http://www.w3.org/1999/xhtml' @@ -165,7 +165,7 @@ def parse_html(data, log=None, decoder=None, preprocessor=None, filename = force_unicode(filename, enc=filesystem_encoding) - if not isinstance(data, unicode_type): + if not isinstance(data, str): if decoder is not None: data = decoder(data) else: @@ -247,7 +247,7 @@ def parse_html(data, log=None, decoder=None, preprocessor=None, nroot = safe_xml_fromstring('') has_body = False for child in list(data): - if isinstance(child.tag, (unicode_type, bytes)) and barename(child.tag) == 'body': + if isinstance(child.tag, (str, bytes)) and barename(child.tag) == 'body': has_body = True break parent = nroot diff --git a/src/calibre/ebooks/oeb/polish/cascade.py b/src/calibre/ebooks/oeb/polish/cascade.py index 2475c906f9..7f670eccdb 100644 --- a/src/calibre/ebooks/oeb/polish/cascade.py +++ b/src/calibre/ebooks/oeb/polish/cascade.py @@ -18,7 +18,7 @@ from calibre.ebooks.oeb.normalize_css import normalizers, DEFAULTS from calibre.ebooks.oeb.stylizer import media_ok, INHERITED from tinycss.fonts3 import serialize_font_family, parse_font_family -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues _html_css_stylesheet = None @@ -233,7 +233,7 @@ def process_sheet(sheet, sheet_name): def defvals(): global _defvals if _defvals is None: - _defvals = {k:Values(Property(k, unicode_type(val)).propertyValue) for k, val in iteritems(DEFAULTS)} + _defvals = {k:Values(Property(k, str(val)).propertyValue) for k, val in iteritems(DEFAULTS)} return _defvals diff --git a/src/calibre/ebooks/oeb/polish/check/parsing.py b/src/calibre/ebooks/oeb/polish/check/parsing.py index 9f06944928..2dbf924a06 100644 --- a/src/calibre/ebooks/oeb/polish/check/parsing.py +++ b/src/calibre/ebooks/oeb/polish/check/parsing.py @@ -17,7 +17,7 @@ from calibre.ebooks.oeb.polish.utils import PositionFinder, guess_type from calibre.ebooks.oeb.polish.check.base import BaseError, WARN, ERROR, INFO from calibre.ebooks.oeb.base import OEB_DOCS, XHTML_NS, urlquote, URL_SAFE, XHTML -from polyglot.builtins import iteritems, unicode_type, error_message +from polyglot.builtins import iteritems, error_message HTML_ENTITTIES = frozenset(html5_entities) XML_ENTITIES = {'lt', 'gt', 'amp', 'apos', 'quot'} @@ -203,7 +203,7 @@ def __init__(self, name, enc): def __call__(self, container): raw = container.raw_data(self.name) - if isinstance(raw, unicode_type): + if isinstance(raw, str): raw, changed = replace_encoding_declarations(raw) if changed: container.open(self.name, 'wb').write(raw.encode('utf-8')) @@ -443,7 +443,7 @@ def __noop(self, *args, **kwargs): info = debug = setLevel = getEffectiveLevel = addHandler = removeHandler = __noop def __handle(self, level, *args): - msg = ' '.join(map(unicode_type, args)) + msg = ' '.join(map(str, args)) line = col = None for pat in pos_pats: m = pat.search(msg) diff --git a/src/calibre/ebooks/oeb/polish/container.py b/src/calibre/ebooks/oeb/polish/container.py index a8f92846a0..ebe3663243 100644 --- a/src/calibre/ebooks/oeb/polish/container.py +++ b/src/calibre/ebooks/oeb/polish/container.py @@ -51,7 +51,7 @@ from calibre.utils.logging import default_log from calibre.utils.xml_parse import safe_xml_fromstring from calibre.utils.zipfile import ZipFile -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.urllib import urlparse exists, join, relpath = os.path.exists, os.path.join, os.path.relpath @@ -166,7 +166,7 @@ def decode(self, data, normalize_to_nfc=True): """ def fix_data(d): return d.replace('\r\n', '\n').replace('\r', '\n') - if isinstance(data, unicode_type): + if isinstance(data, str): return fix_data(data) bom_enc = None if data[:4] in {b'\0\0\xfe\xff', b'\xff\xfe\0\0'}: @@ -697,7 +697,7 @@ def manifest_items_of_type(self, predicate): ''' The names of all manifest items whose media-type matches predicate. `predicate` can be a set, a list, a string or a function taking a single argument, which will be called with the media-type. ''' - if isinstance(predicate, unicode_type): + if isinstance(predicate, str): predicate = predicate.__eq__ elif hasattr(predicate, '__contains__'): predicate = predicate.__contains__ diff --git a/src/calibre/ebooks/oeb/polish/cover.py b/src/calibre/ebooks/oeb/polish/cover.py index 44f9ea6792..801068bfa1 100644 --- a/src/calibre/ebooks/oeb/polish/cover.py +++ b/src/calibre/ebooks/oeb/polish/cover.py @@ -10,7 +10,7 @@ from calibre.ebooks.oeb.base import OPF, OEB_DOCS, XPath, XLINK, xml2text from calibre.ebooks.oeb.polish.replace import replace_links, get_recommended_folders from calibre.utils.imghdr import identify -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def set_azw3_cover(container, cover_path, report, options=None): @@ -384,8 +384,8 @@ def create_epub_cover(container, cover_path, existing_image, options=None): ar = 'xMidYMid meet' if keep_aspect else 'none' templ = CoverManager.SVG_TEMPLATE.replace('__ar__', ar) templ = templ.replace('__viewbox__', '0 0 %d %d'%(width, height)) - templ = templ.replace('__width__', unicode_type(width)) - templ = templ.replace('__height__', unicode_type(height)) + templ = templ.replace('__width__', str(width)) + templ = templ.replace('__height__', str(height)) folder = recommended_folders[tname] if folder: tname = folder + '/' + tname diff --git a/src/calibre/ebooks/oeb/polish/css.py b/src/calibre/ebooks/oeb/polish/css.py index e53185ab2f..891fd7b1ba 100644 --- a/src/calibre/ebooks/oeb/polish/css.py +++ b/src/calibre/ebooks/oeb/polish/css.py @@ -19,7 +19,7 @@ from calibre.ebooks.oeb.polish.pretty import pretty_script_or_style, pretty_xml_tree, serialize from calibre.utils.icu import numeric_sort_key from css_selectors import Select, SelectorError -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot.functools import lru_cache @@ -456,10 +456,10 @@ def sort_sheet(container, sheet_or_text): ''' Sort the rules in a stylesheet. Note that in the general case this can change the effective styles, but for most common sheets, it should be safe. ''' - sheet = container.parse_css(sheet_or_text) if isinstance(sheet_or_text, unicode_type) else sheet_or_text + sheet = container.parse_css(sheet_or_text) if isinstance(sheet_or_text, str) else sheet_or_text def text_sort_key(x): - return numeric_sort_key(unicode_type(x or '')) + return numeric_sort_key(str(x or '')) def selector_sort_key(x): return (x.specificity, text_sort_key(x.selectorText)) diff --git a/src/calibre/ebooks/oeb/polish/parsing.py b/src/calibre/ebooks/oeb/polish/parsing.py index 097b7a53bd..be85e69d43 100644 --- a/src/calibre/ebooks/oeb/polish/parsing.py +++ b/src/calibre/ebooks/oeb/polish/parsing.py @@ -14,7 +14,6 @@ from calibre.utils.xml_parse import safe_xml_fromstring from calibre.ebooks.chardet import xml_to_unicode, strip_encoding_declarations from calibre.utils.cleantext import clean_xml_chars -from polyglot.builtins import unicode_type XHTML_NS = 'http://www.w3.org/1999/xhtml' @@ -84,7 +83,7 @@ def parse(raw, decoder=None, log=None, line_numbers=True, linenumber_attribute=N if linenumber_attribute: for elem in ans.iter(LxmlElement): if elem.sourceline is not None: - elem.set(linenumber_attribute, unicode_type(elem.sourceline)) + elem.set(linenumber_attribute, str(elem.sourceline)) return ans except Exception: if log is not None: diff --git a/src/calibre/ebooks/oeb/polish/spell.py b/src/calibre/ebooks/oeb/polish/spell.py index ed8538ed48..19a436fa79 100644 --- a/src/calibre/ebooks/oeb/polish/spell.py +++ b/src/calibre/ebooks/oeb/polish/spell.py @@ -16,7 +16,7 @@ from calibre.ebooks.oeb.polish.parsing import parse from calibre.ebooks.oeb.polish.toc import find_existing_ncx_toc, find_existing_nav_toc from calibre.utils.icu import ord_string -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems _patterns = None @@ -82,7 +82,7 @@ def filter_words(word): def get_words(text, lang): try: - ans = split_into_words(unicode_type(text), lang) + ans = split_into_words(str(text), lang) except (TypeError, ValueError): return () return list(filter(filter_words, ans)) @@ -318,7 +318,7 @@ def merge_locations(locs1, locs2): def replace(text, original_word, new_word, lang): indices = [] - original_word, new_word, text = unicode_type(original_word), unicode_type(new_word), unicode_type(text) + original_word, new_word, text = str(original_word), str(new_word), str(text) q = text offset = 0 while True: diff --git a/src/calibre/ebooks/oeb/polish/split.py b/src/calibre/ebooks/oeb/polish/split.py index ab9b5a8722..689f7ab3c7 100644 --- a/src/calibre/ebooks/oeb/polish/split.py +++ b/src/calibre/ebooks/oeb/polish/split.py @@ -12,7 +12,7 @@ from calibre.ebooks.oeb.polish.errors import MalformedMarkup from calibre.ebooks.oeb.polish.toc import node_from_loc from calibre.ebooks.oeb.polish.replace import LinkRebaser -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.urllib import urlparse @@ -184,7 +184,7 @@ def split(container, name, loc_or_xpath, before=True, totals=None): ''' root = container.parsed(name) - if isinstance(loc_or_xpath, unicode_type): + if isinstance(loc_or_xpath, str): split_point = root.xpath(loc_or_xpath)[0] else: try: @@ -282,7 +282,7 @@ def multisplit(container, name, xpath, before=True): raise AbortError('Cannot split on the tag') for i, tag in enumerate(nodes): - tag.set('calibre-split-point', unicode_type(i)) + tag.set('calibre-split-point', str(i)) current = name all_names = [name] diff --git a/src/calibre/ebooks/oeb/polish/stats.py b/src/calibre/ebooks/oeb/polish/stats.py index 18adad29d0..028e24ab63 100644 --- a/src/calibre/ebooks/oeb/polish/stats.py +++ b/src/calibre/ebooks/oeb/polish/stats.py @@ -15,7 +15,7 @@ from calibre.ebooks.oeb.base import XHTML, css_text from calibre.ebooks.oeb.polish.cascade import iterrules, resolve_styles, iterdeclaration from calibre.utils.icu import ord_string, safe_chr -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from tinycss.fonts3 import parse_font_family @@ -23,7 +23,7 @@ def normalize_font_properties(font): w = font.get('font-weight', None) if not w and w != 0: w = 'normal' - w = unicode_type(w) + w = str(w) w = {'normal':'400', 'bold':'700'}.get(w, w) if w not in {'100', '200', '300', '400', '500', '600', '700', '800', '900'}: @@ -161,7 +161,7 @@ def get_font_dict(elem, resolve_property, pseudo=None): for p in 'weight', 'style', 'stretch': p = 'font-' + p rp = resolve_property(elem, p) if pseudo is None else resolve_property(elem, pseudo, p) - ans[p] = unicode_type(rp[0].value) + ans[p] = str(rp[0].value) normalize_font_properties(ans) return ans diff --git a/src/calibre/ebooks/oeb/polish/tests/base.py b/src/calibre/ebooks/oeb/polish/tests/base.py index fbdf11cc1e..791b5c4231 100644 --- a/src/calibre/ebooks/oeb/polish/tests/base.py +++ b/src/calibre/ebooks/oeb/polish/tests/base.py @@ -12,7 +12,7 @@ from calibre.ptempfile import PersistentTemporaryDirectory from calibre.utils.logging import DevNull import calibre.ebooks.oeb.polish.container as pc -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def get_cache(): @@ -24,7 +24,7 @@ def get_cache(): def needs_recompile(obj, srcs): - if isinstance(srcs, unicode_type): + if isinstance(srcs, str): srcs = [srcs] try: obj_mtime = os.stat(obj).st_mtime diff --git a/src/calibre/ebooks/oeb/polish/tests/cascade.py b/src/calibre/ebooks/oeb/polish/tests/cascade.py index f74f135d8c..b56ea68286 100644 --- a/src/calibre/ebooks/oeb/polish/tests/cascade.py +++ b/src/calibre/ebooks/oeb/polish/tests/cascade.py @@ -18,7 +18,7 @@ from calibre.ebooks.oeb.polish.stats import StatsCollector, font_keys, normalize_font_properties, prepare_font_rule from calibre.ebooks.oeb.polish.tests.base import BaseTest from calibre.utils.logging import Log, Stream -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class VirtualContainer(ContainerBase): @@ -83,7 +83,7 @@ def test_property(select, resolve_property, selector, name, val=None): elem = next(select(selector)) ans = resolve_property(elem, name) if val is None: - val = unicode_type(DEFAULTS[name]) + val = str(DEFAULTS[name]) self.assertEqual(val, ans.cssText) def test_pseudo_property(select, resolve_pseudo_property, selector, prop, name, val=None, abort_on_missing=False): @@ -94,7 +94,7 @@ def test_pseudo_property(select, resolve_pseudo_property, selector, prop, name, self.assertTrue(ans is None) return if val is None: - val = unicode_type(DEFAULTS[name]) + val = str(DEFAULTS[name]) self.assertEqual(val, ans.cssText) def get_maps(html, styles=None, pseudo=False): diff --git a/src/calibre/ebooks/oeb/polish/tests/container.py b/src/calibre/ebooks/oeb/polish/tests/container.py index 5f54f94059..6da8d73388 100644 --- a/src/calibre/ebooks/oeb/polish/tests/container.py +++ b/src/calibre/ebooks/oeb/polish/tests/container.py @@ -15,7 +15,7 @@ from calibre.ebooks.oeb.polish.split import split, merge from calibre.utils.filenames import nlinks_file from calibre.ptempfile import TemporaryFile, TemporaryDirectory -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues def get_container(*args, **kwargs): @@ -98,7 +98,7 @@ def test_file_rename(self): def new_container(): count[0] += 1 - tdir = os.mkdir(os.path.join(self.tdir, unicode_type(count[0]))) + tdir = os.mkdir(os.path.join(self.tdir, str(count[0]))) return get_container(book, tdir=tdir) # Test simple opf rename diff --git a/src/calibre/ebooks/oeb/polish/tests/structure.py b/src/calibre/ebooks/oeb/polish/tests/structure.py index 5b84ed0220..4d575c73d5 100644 --- a/src/calibre/ebooks/oeb/polish/tests/structure.py +++ b/src/calibre/ebooks/oeb/polish/tests/structure.py @@ -19,7 +19,6 @@ from calibre.ebooks.oeb.base import OEB_DOCS from calibre.ebooks.metadata.book.base import Metadata from calibre.ebooks.metadata.opf3 import CALIBRE_PREFIX -from polyglot.builtins import unicode_type OPF_TEMPLATE = ''' @@ -64,7 +63,7 @@ def create_epub(manifest, spine=(), guide=(), meta_cover=None, ver=3): ''') zf.writestr('content.opf', opf.encode('utf-8')) for name, data, properties in manifest: - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') zf.writestr(name, data or b'\0') buf.seek(0) @@ -78,7 +77,7 @@ class Structure(BaseTest): def create_epub(self, *args, **kw): n = next(counter) - ep = os.path.join(self.tdir, unicode_type(n) + 'book.epub') + ep = os.path.join(self.tdir, str(n) + 'book.epub') with open(ep, 'wb') as f: f.write(create_epub(*args, **kw).getvalue()) c = get_container(ep, tdir=os.path.join(self.tdir, 'container%d' % n), tweak_mode=True) diff --git a/src/calibre/ebooks/oeb/polish/toc.py b/src/calibre/ebooks/oeb/polish/toc.py index 6d23bc2fb6..ad26b86a74 100644 --- a/src/calibre/ebooks/oeb/polish/toc.py +++ b/src/calibre/ebooks/oeb/polish/toc.py @@ -23,7 +23,7 @@ from calibre.ebooks.oeb.polish.pretty import pretty_html_tree from calibre.translations.dynamic import translate from calibre.utils.localization import get_lang, canonicalize_lang, lang_as_iso639_1 -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.urllib import urlparse ns = etree.FunctionNamespace('calibre_xpath_extensions') @@ -173,11 +173,11 @@ def parse_ncx(container, ncx_name): toc_root.lang = toc_root.uid = None for attr, val in iteritems(root.attrib): if attr.endswith('lang'): - toc_root.lang = unicode_type(val) + toc_root.lang = str(val) break for uid in root.xpath('//*[calibre:lower-case(local-name()) = "meta" and @name="dtb:uid"]/@content'): if uid: - toc_root.uid = unicode_type(uid) + toc_root.uid = str(uid) break for pl in root.xpath('//*[calibre:lower-case(local-name()) = "pagelist"]'): for pt in pl.xpath('descendant::*[calibre:lower-case(local-name()) = "pagetarget"]'): @@ -584,9 +584,9 @@ def create_ncx(toc, to_href, btitle, lang, uid): nsmap={None: NCX_NS}) head = etree.SubElement(ncx, NCX('head')) etree.SubElement(head, NCX('meta'), - name='dtb:uid', content=unicode_type(uid)) + name='dtb:uid', content=str(uid)) etree.SubElement(head, NCX('meta'), - name='dtb:depth', content=unicode_type(toc.depth)) + name='dtb:depth', content=str(toc.depth)) generator = ''.join(['calibre (', __version__, ')']) etree.SubElement(head, NCX('meta'), name='dtb:generator', content=generator) @@ -604,7 +604,7 @@ def process_node(xml_parent, toc_parent): for child in toc_parent: play_order['c'] += 1 point = etree.SubElement(xml_parent, NCX('navPoint'), id='num_%d' % play_order['c'], - playOrder=unicode_type(play_order['c'])) + playOrder=str(play_order['c'])) label = etree.SubElement(point, NCX('navLabel')) title = child.title if title: @@ -770,7 +770,7 @@ def create_li(ol, entry): for entry in toc.page_list: if container.has_name(entry['dest']) and container.mime_map[entry['dest']] in OEB_DOCS: a = create_li(ol, entry) - a.text = unicode_type(entry['pagenum']) + a.text = str(entry['pagenum']) pretty_xml_tree(nav) collapse_li(nav) container.replace(tocname, root) diff --git a/src/calibre/ebooks/oeb/reader.py b/src/calibre/ebooks/oeb/reader.py index 4037cbe98f..961187a91a 100644 --- a/src/calibre/ebooks/oeb/reader.py +++ b/src/calibre/ebooks/oeb/reader.py @@ -27,7 +27,6 @@ from calibre.ptempfile import TemporaryDirectory from calibre.constants import __appname__, __version__ from calibre import guess_type, xml_replace_entities -from polyglot.builtins import unicode_type from polyglot.urllib import unquote, urldefrag, urlparse __all__ = ['OEBReader'] @@ -145,7 +144,7 @@ def _metadata_from_opf(self, opf): dict(a=__appname__, v=__version__) meta_info_to_oeb_metadata(mi, self.oeb.metadata, self.logger) m = self.oeb.metadata - m.add('identifier', unicode_type(uuid.uuid4()), id='uuid_id', scheme='uuid') + m.add('identifier', str(uuid.uuid4()), id='uuid_id', scheme='uuid') self.oeb.uid = self.oeb.metadata.identifier[-1] if not m.title: m.add('title', self.oeb.translate(__('Unknown'))) @@ -448,7 +447,7 @@ def _toc_from_ncx(self, item): ncx = item.data title = ''.join(xpath(ncx, 'ncx:docTitle/ncx:text/text()')) title = COLLAPSE_RE.sub(' ', title.strip()) - title = title or unicode_type(self.oeb.metadata.title[0]) + title = title or str(self.oeb.metadata.title[0]) toc = self.oeb.toc toc.title = title navmaps = xpath(ncx, 'ncx:navMap') @@ -635,7 +634,7 @@ def _cover_from_html(self, hcover): def _locate_cover_image(self): if self.oeb.metadata.cover: - id = unicode_type(self.oeb.metadata.cover[0]) + id = str(self.oeb.metadata.cover[0]) item = self.oeb.manifest.ids.get(id, None) if item is not None and item.media_type in OEB_IMAGES: return item diff --git a/src/calibre/ebooks/oeb/stylizer.py b/src/calibre/ebooks/oeb/stylizer.py index dc129b3bce..55551116f3 100644 --- a/src/calibre/ebooks/oeb/stylizer.py +++ b/src/calibre/ebooks/oeb/stylizer.py @@ -21,7 +21,7 @@ from calibre.ebooks.oeb.base import XHTML, XHTML_NS, CSS_MIME, OEB_STYLES, xpath, urlnormalize from calibre.ebooks.oeb.normalize_css import DEFAULTS, normalizers from css_selectors import Select, SelectorError, INAPPROPRIATE_PSEUDO_CLASSES -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from tinycss.media3 import CSSMedia3Parser css_parser_log.setLevel(logging.WARN) @@ -324,7 +324,7 @@ def __init__(self, tree, path, oeb, opts, profile=None, for x in elem.iter('*'): if x.text: punctuation_chars = [] - text = unicode_type(x.text) + text = str(x.text) while text: category = unicodedata.category(text[0]) if category[0] not in {'P', 'Z'}: @@ -603,7 +603,7 @@ def img_dimension(self, attr, img_size): x = self._style.get(attr) if x is not None: if x == 'auto': - ans = self._unit_convert(unicode_type(img_size) + 'px', base=base) + ans = self._unit_convert(str(img_size) + 'px', base=base) else: x = self._unit_convert(x, base=base) if isinstance(x, numbers.Number): @@ -615,7 +615,7 @@ def img_dimension(self, attr, img_size): if isinstance(x, numbers.Number): ans = x if ans is None: - ans = self._unit_convert(unicode_type(img_size) + 'px', base=base) + ans = self._unit_convert(str(img_size) + 'px', base=base) maa = self._style.get('max-' + attr) if maa is not None: x = self._unit_convert(maa, base=base) @@ -651,12 +651,12 @@ def width(self): result = base else: result = self._unit_convert(width, base=base) - if isinstance(result, (unicode_type, bytes)): + if isinstance(result, (str, bytes)): result = self._profile.width self._width = result if 'max-width' in self._style: result = self._unit_convert(self._style['max-width'], base=base) - if isinstance(result, (unicode_type, bytes)): + if isinstance(result, (str, bytes)): result = self._width if result < self._width: self._width = result @@ -688,12 +688,12 @@ def height(self): result = base else: result = self._unit_convert(height, base=base) - if isinstance(result, (unicode_type, bytes)): + if isinstance(result, (str, bytes)): result = self._profile.height self._height = result if 'max-height' in self._style: result = self._unit_convert(self._style['max-height'], base=base) - if isinstance(result, (unicode_type, bytes)): + if isinstance(result, (str, bytes)): result = self._height if result < self._height: self._height = result diff --git a/src/calibre/ebooks/oeb/transforms/cover.py b/src/calibre/ebooks/oeb/transforms/cover.py index 158ce3554d..ccbd567f95 100644 --- a/src/calibre/ebooks/oeb/transforms/cover.py +++ b/src/calibre/ebooks/oeb/transforms/cover.py @@ -11,7 +11,6 @@ from calibre import guess_type from calibre.utils.imghdr import identify from calibre.utils.xml_parse import safe_xml_fromstring -from polyglot.builtins import unicode_type from polyglot.urllib import unquote @@ -92,14 +91,14 @@ def default_cover(self): return None self.log('Generating default cover') m = self.oeb.metadata - title = unicode_type(m.title[0]) - authors = [unicode_type(x) for x in m.creator if x.role == 'aut'] + title = str(m.title[0]) + authors = [str(x) for x in m.creator if x.role == 'aut'] try: from calibre.ebooks.covers import create_cover series = series_index = None if m.series: try: - series, series_index = unicode_type(m.series[0]), m.series_index[0] + series, series_index = str(m.series[0]), m.series_index[0] except IndexError: pass img_data = create_cover(title, authors, series, series_index) @@ -146,9 +145,9 @@ def insert_cover(self): self.svg_template = self.svg_template.replace('__viewbox__', '0 0 %d %d'%(width, height)) self.svg_template = self.svg_template.replace('__width__', - unicode_type(width)) + str(width)) self.svg_template = self.svg_template.replace('__height__', - unicode_type(height)) + str(height)) if href is not None: templ = self.non_svg_template if self.no_svg_cover \ diff --git a/src/calibre/ebooks/oeb/transforms/embed_fonts.py b/src/calibre/ebooks/oeb/transforms/embed_fonts.py index fcff0aabcf..ecd12341e1 100644 --- a/src/calibre/ebooks/oeb/transforms/embed_fonts.py +++ b/src/calibre/ebooks/oeb/transforms/embed_fonts.py @@ -17,11 +17,11 @@ from calibre.utils.filenames import ascii_filename from calibre.utils.fonts.scanner import font_scanner, NoFonts from calibre.ebooks.oeb.polish.embed import font_key -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def font_families_from_style(style): - return [unicode_type(f) for f in style.get('font-family', []) if unicode_type(f).lower() not in { + return [str(f) for f in style.get('font-family', []) if str(f).lower() not in { 'serif', 'sansserif', 'sans-serif', 'fantasy', 'cursive', 'monospace'}] @@ -39,7 +39,7 @@ def used_font(style, embedded_fonts): ff = font_families_from_style(style) if not ff: return False, None - lnames = {unicode_type(x).lower() for x in ff} + lnames = {str(x).lower() for x in ff} matching_set = [] diff --git a/src/calibre/ebooks/oeb/transforms/flatcss.py b/src/calibre/ebooks/oeb/transforms/flatcss.py index b0bf43984f..ca74dc4a66 100644 --- a/src/calibre/ebooks/oeb/transforms/flatcss.py +++ b/src/calibre/ebooks/oeb/transforms/flatcss.py @@ -21,7 +21,7 @@ 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, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, string_or_bytes COLLAPSE = re.compile(r'[ \t\r\n\v]+') STRIPNUM = re.compile(r'[-0-9]+$') @@ -251,7 +251,7 @@ def get_embed_font_info(self, family, failure_critical=True): cfont = { 'font-family': '"%s"'%font['font-family'], - 'panose-1': ' '.join(map(unicode_type, font['panose'])), + 'panose-1': ' '.join(map(str, font['panose'])), 'src': 'url(%s)'%item.href, } @@ -477,7 +477,7 @@ def force_int(raw): minlh = self.context.minimum_line_height / 100. slh = style['line-height'] if not is_drop_cap and isinstance(slh, numbers.Number) and slh < minlh * fsize: - cssdict['line-height'] = unicode_type(minlh) + cssdict['line-height'] = str(minlh) except Exception: self.oeb.logger.exception('Failed to set minimum line-height') @@ -539,7 +539,7 @@ def force_int(raw): if css in styles: match = styles[css] else: - match = klass + unicode_type(names[klass] or '') + match = klass + str(names[klass] or '') styles[css] = match names[klass] += 1 node.attrib['class'] = match @@ -559,7 +559,7 @@ def force_int(raw): # then the class attribute for a.x tags will contain both # that class and the class for a.x:hover, which is wrong. klass = 'pcalibre' - match = klass + unicode_type(names[klass] or '') + match = klass + str(names[klass] or '') pstyles[css] = match names[klass] += 1 keep_classes.add(match) diff --git a/src/calibre/ebooks/oeb/transforms/htmltoc.py b/src/calibre/ebooks/oeb/transforms/htmltoc.py index 3de45ebdf2..a4a4ad7b1a 100644 --- a/src/calibre/ebooks/oeb/transforms/htmltoc.py +++ b/src/calibre/ebooks/oeb/transforms/htmltoc.py @@ -9,7 +9,6 @@ from calibre.ebooks.oeb.base import XML, XHTML, XHTML_NS from calibre.ebooks.oeb.base import XHTML_MIME, CSS_MIME from calibre.ebooks.oeb.base import element, XPath -from polyglot.builtins import unicode_type __all__ = ['HTMLTOCAdder'] @@ -95,7 +94,7 @@ def __call__(self, oeb, context): style = 'nested' id, css_href = oeb.manifest.generate('tocstyle', 'tocstyle.css') oeb.manifest.add(id, css_href, CSS_MIME, data=STYLE_CSS[style]) - language = unicode_type(oeb.metadata.language[0]) + language = str(oeb.metadata.language[0]) contents = element(None, XHTML('html'), nsmap={None: XHTML_NS}, attrib={XML('lang'): language}) head = element(contents, XHTML('head')) diff --git a/src/calibre/ebooks/oeb/transforms/jacket.py b/src/calibre/ebooks/oeb/transforms/jacket.py index 8b08e40ba1..0b286e7509 100644 --- a/src/calibre/ebooks/oeb/transforms/jacket.py +++ b/src/calibre/ebooks/oeb/transforms/jacket.py @@ -25,7 +25,6 @@ from calibre.utils.config import tweaks from calibre.utils.date import as_local_time, format_date, is_date_undefined from calibre.utils.icu import sort_key -from polyglot.builtins import unicode_type JACKET_XPATH = '//h:meta[@name="calibre-content" and @content="jacket"]' @@ -108,22 +107,22 @@ def insert_metadata(self, mi): self.log('Inserting metadata into book...') try: - tags = list(map(unicode_type, self.oeb.metadata.subject)) + tags = list(map(str, self.oeb.metadata.subject)) except Exception: tags = [] try: - comments = unicode_type(self.oeb.metadata.description[0]) + comments = str(self.oeb.metadata.description[0]) except: comments = '' try: - title = unicode_type(self.oeb.metadata.title[0]) + title = str(self.oeb.metadata.title[0]) except: title = _('Unknown') try: - authors = list(map(unicode_type, self.oeb.metadata.creator)) + authors = list(map(str, self.oeb.metadata.creator)) except: authors = [_('Unknown')] @@ -180,7 +179,7 @@ def get_rating(rating, rchar, e_rchar): return ans -class Series(unicode_type): +class Series(str): def __new__(self, series, series_index): if series and series_index is not None: @@ -190,7 +189,7 @@ def __new__(self, series, series_index): escape(series), escape(fmt_sidx(series_index, use_roman=False))) else: combined = roman = escape(series or u'') - s = unicode_type.__new__(self, combined) + s = str.__new__(self, combined) s.roman = roman s.name = escape(series or '') s.number = escape(fmt_sidx(series_index or 1.0, use_roman=False)) @@ -219,11 +218,11 @@ def __getattr__(self, template): return '' -class Tags(unicode_type): +class Tags(str): def __new__(self, tags, output_profile): tags = [escape(x) for x in tags or ()] - t = unicode_type.__new__(self, ', '.join(tags)) + t = str.__new__(self, ', '.join(tags)) t.alphabetical = ', '.join(sorted(tags, key=sort_key)) t.tags_list = tags return t diff --git a/src/calibre/ebooks/oeb/transforms/rasterize.py b/src/calibre/ebooks/oeb/transforms/rasterize.py index bacae3d8ee..67a61a40d2 100644 --- a/src/calibre/ebooks/oeb/transforms/rasterize.py +++ b/src/calibre/ebooks/oeb/transforms/rasterize.py @@ -17,7 +17,6 @@ from calibre.ebooks.oeb.stylizer import Stylizer from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.imghdr import what -from polyglot.builtins import unicode_type from polyglot.urllib import urldefrag IMAGE_TAGS = {XHTML('img'), XHTML('object')} @@ -77,7 +76,7 @@ def rasterize_svg(self, elem, width=0, height=0, format='PNG'): logger.info('Found SVG image height in %, trying to convert...') try: h = float(image.get('height').replace('%', ''))/100. - image.set('height', unicode_type(h*sizes[1])) + image.set('height', str(h*sizes[1])) except: logger.exception('Failed to convert percentage height:', image.get('height')) @@ -223,11 +222,11 @@ def rasterize_cover(self): covers = self.oeb.metadata.cover if not covers: return - if unicode_type(covers[0]) not in self.oeb.manifest.ids: + if str(covers[0]) not in self.oeb.manifest.ids: self.oeb.logger.warn('Cover not in manifest, skipping.') self.oeb.metadata.clear('cover') return - cover = self.oeb.manifest.ids[unicode_type(covers[0])] + cover = self.oeb.manifest.ids[str(covers[0])] if not cover.media_type == SVG_MIME: return width = (self.profile.width / 72) * self.profile.dpi diff --git a/src/calibre/ebooks/oeb/transforms/split.py b/src/calibre/ebooks/oeb/transforms/split.py index 9e3033239d..ff423da6c4 100644 --- a/src/calibre/ebooks/oeb/transforms/split.py +++ b/src/calibre/ebooks/oeb/transforms/split.py @@ -20,7 +20,7 @@ from calibre.ebooks.oeb.base import (OEB_STYLES, XPNSMAP as NAMESPACES, urldefrag, rewrite_links, XHTML, urlnormalize) from calibre.ebooks.oeb.polish.split import do_split -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.urllib import unquote from css_selectors import Select, SelectorError @@ -123,7 +123,7 @@ def find_page_breaks(self, item): for i, elem in enumerate(item.data.iter('*')): try: - elem.set('pb_order', unicode_type(i)) + elem.set('pb_order', str(i)) except TypeError: # Can't set attributes on comment nodes etc. continue diff --git a/src/calibre/ebooks/oeb/transforms/structure.py b/src/calibre/ebooks/oeb/transforms/structure.py index bea143006b..53551feda7 100644 --- a/src/calibre/ebooks/oeb/transforms/structure.py +++ b/src/calibre/ebooks/oeb/transforms/structure.py @@ -13,7 +13,7 @@ from calibre.ebooks.oeb.base import XPNSMAP, TOC, XHTML, xml2text, barename from calibre.ebooks import ConversionError -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues from polyglot.urllib import urlparse @@ -124,7 +124,7 @@ def detect_start_reading(self): elem = matches[0] eid = elem.get('id', None) if not eid: - eid = 'start_reading_at_'+unicode_type(uuid.uuid4()).replace('-', '') + eid = 'start_reading_at_'+str(uuid.uuid4()).replace('-', '') elem.set('id', eid) if 'text' in self.oeb.guide: self.oeb.guide.remove('text') diff --git a/src/calibre/ebooks/oeb/transforms/subset.py b/src/calibre/ebooks/oeb/transforms/subset.py index 392264eae5..0e62aff9b4 100644 --- a/src/calibre/ebooks/oeb/transforms/subset.py +++ b/src/calibre/ebooks/oeb/transforms/subset.py @@ -10,7 +10,7 @@ from calibre.ebooks.oeb.base import urlnormalize, css_text from calibre.utils.fonts.sfnt.subset import subset, NoGlyphs, UnsupportedFont -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from tinycss.fonts3 import parse_font_family @@ -35,7 +35,7 @@ def get_font_properties(rule, default=None): except (IndexError, KeyError, AttributeError, TypeError, ValueError): val = None if q in {'src', 'font-family'} else default if q in {'font-weight', 'font-stretch', 'font-style'}: - val = unicode_type(val).lower() if (val or val == 0) else val + val = str(val).lower() if (val or val == 0) else val if val == 'inherit': val = default if q == 'font-weight': @@ -236,7 +236,7 @@ def used_font(self, style): no match is found (can happen if no family matches). ''' ff = style.get('font-family', []) - lnames = {unicode_type(x).lower() for x in ff} + lnames = {str(x).lower() for x in ff} matching_set = [] # Filter on font-family diff --git a/src/calibre/ebooks/pdb/ereader/reader132.py b/src/calibre/ebooks/pdb/ereader/reader132.py index 820c8e6734..4e653de423 100644 --- a/src/calibre/ebooks/pdb/ereader/reader132.py +++ b/src/calibre/ebooks/pdb/ereader/reader132.py @@ -19,7 +19,6 @@ from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.pdb.ereader import EreaderError from calibre.ebooks.pdb.formatreader import FormatReader -from polyglot.builtins import unicode_type class HeaderRecord: @@ -115,7 +114,7 @@ def extract_content(self, output_dir): os.makedirs(output_dir) title = self.mi.title - if not isinstance(title, unicode_type): + if not isinstance(title, str): title = title.decode('utf-8', 'replace') html = '%s' % title diff --git a/src/calibre/ebooks/pdb/ereader/reader202.py b/src/calibre/ebooks/pdb/ereader/reader202.py index f328381787..9ecec974af 100644 --- a/src/calibre/ebooks/pdb/ereader/reader202.py +++ b/src/calibre/ebooks/pdb/ereader/reader202.py @@ -15,7 +15,7 @@ from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.pdb.ereader import EreaderError from calibre.ebooks.pdb.formatreader import FormatReader -from polyglot.builtins import as_unicode, unicode_type +from polyglot.builtins import as_unicode class HeaderRecord: @@ -98,7 +98,7 @@ def extract_content(self, output_dir): pml += self.get_text_page(i) title = self.mi.title - if not isinstance(title, unicode_type): + if not isinstance(title, str): title = title.decode('utf-8', 'replace') html = '%s%s' % \ diff --git a/src/calibre/ebooks/pdb/ereader/writer.py b/src/calibre/ebooks/pdb/ereader/writer.py index 4e5043ad63..cae9f3838c 100644 --- a/src/calibre/ebooks/pdb/ereader/writer.py +++ b/src/calibre/ebooks/pdb/ereader/writer.py @@ -19,7 +19,7 @@ from calibre.ebooks.pdb.formatwriter import FormatWriter from calibre.ebooks.pdb.header import PdbHeaderBuilder from calibre.ebooks.pml.pmlml import PMLMLizer -from polyglot.builtins import unicode_type, as_bytes +from polyglot.builtins import as_bytes IDENTITY = 'PNRdPPrs' @@ -36,7 +36,7 @@ def __init__(self, opts, log): def write_content(self, oeb_book, out_stream, metadata=None): pmlmlizer = PMLMLizer(self.log) - pml = unicode_type(pmlmlizer.extract_content(oeb_book, self.opts)).encode('cp1252', 'replace') + pml = str(pmlmlizer.extract_content(oeb_book, self.opts)).encode('cp1252', 'replace') text, text_sizes = self._text(pml) chapter_index = self._index_item(br'(?s)\\C(?P[0-4])="(?P.+?)"', pml) diff --git a/src/calibre/ebooks/pdf/html_writer.py b/src/calibre/ebooks/pdf/html_writer.py index d261e51a7a..b614de420b 100644 --- a/src/calibre/ebooks/pdf/html_writer.py +++ b/src/calibre/ebooks/pdf/html_writer.py @@ -44,7 +44,7 @@ dedup_type3_fonts, get_podofo, remove_unused_fonts, set_metadata_implementation ) from calibre.utils.short_uuid import uuid4 -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.urllib import urlparse OK, KILL_SIGNAL = range(0, 2) @@ -645,7 +645,7 @@ def get_page_number_display_map(render_manager, opts, num_pages, log): for (var i=1; i <= NUM_PAGES; i++) ans[i] = map_num(i); JSON.stringify(ans); '''.replace('MAP_EXPRESSION', json.dumps(opts.pdf_page_number_map), 1).replace( - 'NUM_PAGES', unicode_type(num_pages), 1) + 'NUM_PAGES', str(num_pages), 1) result = render_manager.evaljs(js) try: result = json.loads(result) @@ -933,10 +933,10 @@ def create_container(page_num, margins): return ans def format_template(template, page_num, height): - template = template.replace('_TOP_LEVEL_SECTION_PAGES_', unicode_type(toplevel_pagenum_map[page_num - 1])) - template = template.replace('_TOP_LEVEL_SECTION_PAGENUM_', unicode_type(toplevel_pages_map[page_num - 1])) - template = template.replace('_TOTAL_PAGES_', unicode_type(pages_in_doc)) - template = template.replace('_PAGENUM_', unicode_type(page_number_display_map[page_num])) + template = template.replace('_TOP_LEVEL_SECTION_PAGES_', str(toplevel_pagenum_map[page_num - 1])) + template = template.replace('_TOP_LEVEL_SECTION_PAGENUM_', str(toplevel_pages_map[page_num - 1])) + template = template.replace('_TOTAL_PAGES_', str(pages_in_doc)) + template = template.replace('_PAGENUM_', str(page_number_display_map[page_num])) template = template.replace('_TITLE_', prepare_string_for_xml(pdf_metadata.title, True)) template = template.replace('_AUTHOR_', prepare_string_for_xml(pdf_metadata.author, True)) template = template.replace('_TOP_LEVEL_SECTION_', prepare_string_for_xml(toplevel_toc_map[page_num - 1])) diff --git a/src/calibre/ebooks/pdf/render/common.py b/src/calibre/ebooks/pdf/render/common.py index 9cfe82a9bf..e41343824e 100644 --- a/src/calibre/ebooks/pdf/render/common.py +++ b/src/calibre/ebooks/pdf/render/common.py @@ -11,7 +11,7 @@ from datetime import datetime from calibre.utils.logging import default_log -from polyglot.builtins import iteritems, unicode_type, codepoint_to_chr +from polyglot.builtins import iteritems, codepoint_to_chr from polyglot.binary import as_hex_bytes from calibre_extensions.speedup import pdf_float @@ -57,7 +57,7 @@ def fmtnum(o): if isinstance(o, float): return pdf_float(o) - return unicode_type(o) + return str(o) def serialize(o, stream): @@ -67,7 +67,7 @@ def serialize(o, stream): # Must check bool before int as bools are subclasses of int stream.write_raw(b'true' if o else b'false') elif isinstance(o, numbers.Integral): - stream.write_raw(unicode_type(o).encode('ascii')) + stream.write_raw(str(o).encode('ascii')) elif hasattr(o, 'pdf_serialize'): o.pdf_serialize(stream) elif o is None: @@ -81,7 +81,7 @@ def serialize(o, stream): raise ValueError('Unknown object: %r'%o) -class Name(unicode_type): +class Name(str): def pdf_serialize(self, stream): raw = self.encode('ascii') @@ -118,7 +118,7 @@ def escape_pdf_string(bytestring): return bytes(ba) -class String(unicode_type): +class String(str): def pdf_serialize(self, stream): try: @@ -130,7 +130,7 @@ def pdf_serialize(self, stream): stream.write(b'('+escape_pdf_string(raw)+b')') -class UTF16String(unicode_type): +class UTF16String(str): def pdf_serialize(self, stream): raw = codecs.BOM_UTF16_BE + self.encode('utf-16-be') diff --git a/src/calibre/ebooks/pdf/render/fonts.py b/src/calibre/ebooks/pdf/render/fonts.py index 0727a0a1a0..5ddd7e4f2f 100644 --- a/src/calibre/ebooks/pdf/render/fonts.py +++ b/src/calibre/ebooks/pdf/render/fonts.py @@ -10,7 +10,7 @@ from itertools import groupby from operator import itemgetter from collections import Counter, OrderedDict -from polyglot.builtins import iteritems, unicode_type, codepoint_to_chr +from polyglot.builtins import iteritems, codepoint_to_chr from calibre import as_unicode from calibre.ebooks.pdf.render.common import (Array, String, Stream, @@ -122,7 +122,7 @@ class Font: def __init__(self, metrics, num, objects, compress): self.metrics, self.compress = metrics, compress self.is_otf = self.metrics.is_otf - self.subset_tag = unicode_type( + self.subset_tag = str( re.sub('.', lambda m: codepoint_to_chr(int(m.group())+ord('A')), oct(num).replace('o', '') )).rjust(6, 'A') self.font_stream = FontStream(metrics.is_otf, compress=compress) diff --git a/src/calibre/ebooks/pml/pmlml.py b/src/calibre/ebooks/pml/pmlml.py index 83700ddf11..3b3853ef91 100644 --- a/src/calibre/ebooks/pml/pmlml.py +++ b/src/calibre/ebooks/pml/pmlml.py @@ -16,7 +16,7 @@ from calibre.ebooks.pdb.ereader import image_name from calibre.utils.xml_parse import safe_xml_fromstring from calibre.ebooks.pml import unipmlcode -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes TAG_MAP = { 'b' : 'B', @@ -177,7 +177,7 @@ def prepare_string_for_pml(self, text): def prepare_text(self, text): # Replace empty paragraphs with \c pml codes used to denote empty lines. - text = re.sub(unicode_type(r'(?<=

)\s*]*>[\xc2\xa0\s]*

'), r'\\c\n\\c', text) + text = re.sub(r'(?<=

)\s*]*>[\xc2\xa0\s]*

', r'\\c\n\\c', text) return text def clean_text(self, text): diff --git a/src/calibre/ebooks/rb/__init__.py b/src/calibre/ebooks/rb/__init__.py index 4a44bf10e3..6d0b69b892 100644 --- a/src/calibre/ebooks/rb/__init__.py +++ b/src/calibre/ebooks/rb/__init__.py @@ -7,7 +7,6 @@ import os -from polyglot.builtins import unicode_type HEADER = b'\xb0\x0c\xb0\x0c\x02\x00NUVO\x00\x00\x00\x00' @@ -24,7 +23,7 @@ def unique_name(name, used_names): ext = os.path.splitext(name)[1][:3] base_name = name[:22] for i in range(0, 9999): - name = '%s-%s.%s' % (unicode_type(i).rjust('0', 4)[:4], base_name, ext) + name = '%s-%s.%s' % (str(i).rjust('0', 4)[:4], base_name, ext) if name not in used_names: break return name diff --git a/src/calibre/ebooks/readability/htmls.py b/src/calibre/ebooks/readability/htmls.py index 4a72f053f7..834b5d45ce 100644 --- a/src/calibre/ebooks/readability/htmls.py +++ b/src/calibre/ebooks/readability/htmls.py @@ -7,7 +7,7 @@ from calibre.ebooks.readability.cleaners import normalize_spaces, clean_attributes from calibre.ebooks.chardet import xml_to_unicode -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def build_doc(page): @@ -122,5 +122,5 @@ def shorten_title(doc): def get_body(doc): [elem.drop_tree() for elem in doc.xpath('.//script | .//link | .//style')] - raw_html = unicode_type(tostring(doc.body or doc)) + raw_html = str(tostring(doc.body or doc)) return clean_attributes(raw_html) diff --git a/src/calibre/ebooks/readability/readability.py b/src/calibre/ebooks/readability/readability.py index 4853101aa0..cdd77cb542 100644 --- a/src/calibre/ebooks/readability/readability.py +++ b/src/calibre/ebooks/readability/readability.py @@ -5,7 +5,7 @@ import re, sys from collections import defaultdict -from polyglot.builtins import reraise, unicode_type +from polyglot.builtins import reraise from lxml.html import (fragment_fromstring, document_fromstring, tostring as htostring) @@ -15,7 +15,7 @@ def tounicode(tree_or_node, **kwargs): - kwargs['encoding'] = unicode_type + kwargs['encoding'] = str return htostring(tree_or_node, **kwargs) @@ -156,7 +156,7 @@ def summary(self): return cleaned_article except Exception as e: self.log.exception('error getting summary: ') - reraise(Unparsable, Unparsable(unicode_type(e)), sys.exc_info()[2]) + reraise(Unparsable, Unparsable(str(e)), sys.exc_info()[2]) def get_article(self, candidates, best_candidate): # Now that we have the top candidate, look through its siblings for content that might also be related. @@ -216,7 +216,7 @@ def get_link_density(self, elem): def score_paragraphs(self, ): MIN_LEN = self.options.get('min_text_length', self.TEXT_LENGTH_THRESHOLD) candidates = {} - # self.debug(unicode_type([describe(node) for node in self.tags(self.html, "div")])) + # self.debug(str([describe(node) for node in self.tags(self.html, "div")])) ordered = [] for elem in self.tags(self.html, "p", "pre", "td"): @@ -313,7 +313,7 @@ def remove_unlikely_candidates(self): def transform_misused_divs_into_paragraphs(self): for elem in self.tags(self.html, 'div'): # transform
s that do not contain other block elements into

s - if not REGEXES['divToPElementsRe'].search(unicode_type(''.join(map(tounicode, list(elem))))): + if not REGEXES['divToPElementsRe'].search(str(''.join(map(tounicode, list(elem))))): # self.debug("Altering %s to p" % (describe(elem))) elem.tag = "p" # print("Fixed element "+describe(elem)) @@ -457,7 +457,7 @@ def sanitize(self, node, candidates): siblings.append(sib_content_length) if j == x: break - # self.debug(unicode_type(siblings)) + # self.debug(str(siblings)) if siblings and sum(siblings) > 1000 : to_remove = False self.debug("Allowing %s" % describe(el)) diff --git a/src/calibre/ebooks/rtf/rtfml.py b/src/calibre/ebooks/rtf/rtfml.py index 654c5803cd..e91b4d33e6 100644 --- a/src/calibre/ebooks/rtf/rtfml.py +++ b/src/calibre/ebooks/rtf/rtfml.py @@ -19,7 +19,7 @@ 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 unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes TAGS = { 'b': '\\b', @@ -78,7 +78,7 @@ def txt2rtf(text): text = text.replace('}', r'\'7d') text = text.replace('\\', r'\'5c') - if not isinstance(text, unicode_type): + if not isinstance(text, str): return text buf = io.StringIO() diff --git a/src/calibre/ebooks/rtf2xml/ParseRtf.py b/src/calibre/ebooks/rtf2xml/ParseRtf.py index 3c7065eb69..3347f1d4f0 100644 --- a/src/calibre/ebooks/rtf2xml/ParseRtf.py +++ b/src/calibre/ebooks/rtf2xml/ParseRtf.py @@ -26,7 +26,6 @@ body_styles, preamble_rest, group_styles, \ inline from calibre.ebooks.rtf2xml.old_rtf import OldRtf -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -250,7 +249,7 @@ def parse_rtf(self): enc = encode_obj.get_codepage() # TODO: to check if cp is a good idea or if I should use a dict to convert enc = 'cp' + enc - msg = '%s\nException in token processing' % unicode_type(msg) + msg = '%s\nException in token processing' % str(msg) if check_encoding_obj.check_encoding(self.__file, enc): file_name = self.__file if isinstance(self.__file, bytes) \ else self.__file.encode('utf-8') diff --git a/src/calibre/ebooks/rtf2xml/check_encoding.py b/src/calibre/ebooks/rtf2xml/check_encoding.py index 1c14d66c3f..053d058100 100644 --- a/src/calibre/ebooks/rtf2xml/check_encoding.py +++ b/src/calibre/ebooks/rtf2xml/check_encoding.py @@ -3,7 +3,6 @@ import sys -from polyglot.builtins import unicode_type class CheckEncoding: @@ -18,7 +17,7 @@ def __get_position_error(self, line, encoding, line_num): try: char.decode(encoding) except ValueError as msg: - sys.stderr.write('line: %s char: %s\n%s\n' % (line_num, char_position, unicode_type(msg))) + sys.stderr.write('line: %s char: %s\n%s\n' % (line_num, char_position, str(msg))) def check_encoding(self, path, encoding='us-ascii', verbose=True): line_num = 0 diff --git a/src/calibre/ebooks/rtf2xml/footnote.py b/src/calibre/ebooks/rtf2xml/footnote.py index c6b7c8fdb2..e48d15be20 100644 --- a/src/calibre/ebooks/rtf2xml/footnote.py +++ b/src/calibre/ebooks/rtf2xml/footnote.py @@ -15,7 +15,6 @@ from calibre.ebooks.rtf2xml import copy from calibre.ptempfile import better_mktemp -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -58,7 +57,7 @@ def __in_footnote_func(self, line): if self.__first_line: self.__first_line_func(line) if self.__token_info == 'cw 3: sys.stderr.write( 'Old rtf construction %s (bracket %s, line %s)\n' % ( - self.__inline_info, unicode_type(self.__ob_group), line_num) + self.__inline_info, str(self.__ob_group), line_num) ) return True self.__previous_token = line[6:16] diff --git a/src/calibre/ebooks/rtf2xml/paragraph_def.py b/src/calibre/ebooks/rtf2xml/paragraph_def.py index e1992c34b1..3fa89c9b82 100644 --- a/src/calibre/ebooks/rtf2xml/paragraph_def.py +++ b/src/calibre/ebooks/rtf2xml/paragraph_def.py @@ -15,7 +15,6 @@ from calibre.ebooks.rtf2xml import copy, border_parse from calibre.ptempfile import better_mktemp -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -624,7 +623,7 @@ def __get_num_of_style(self): num = len(self.__style_num_strings) new_style = 1 num = '%04d' % num - self.__att_val_dict['style-num'] = 's' + unicode_type(num) + self.__att_val_dict['style-num'] = 's' + str(num) if new_style: self.__write_body_styles() diff --git a/src/calibre/ebooks/rtf2xml/pict.py b/src/calibre/ebooks/rtf2xml/pict.py index 2298dc98fc..536136a8b1 100644 --- a/src/calibre/ebooks/rtf2xml/pict.py +++ b/src/calibre/ebooks/rtf2xml/pict.py @@ -15,7 +15,6 @@ from calibre.ebooks.rtf2xml import copy from calibre.ptempfile import better_mktemp -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -78,7 +77,7 @@ def __make_dir(self): try: os.mkdir(self.__dir_name) except OSError as msg: - msg = "%sCouldn't make directory '%s':\n" % (unicode_type(msg), self.__dir_name) + msg = "%sCouldn't make directory '%s':\n" % (str(msg), self.__dir_name) raise self.__bug_handler else: if self.__run_level > 1: diff --git a/src/calibre/ebooks/rtf2xml/process_tokens.py b/src/calibre/ebooks/rtf2xml/process_tokens.py index 66f9d8192b..25ae382f51 100644 --- a/src/calibre/ebooks/rtf2xml/process_tokens.py +++ b/src/calibre/ebooks/rtf2xml/process_tokens.py @@ -15,7 +15,6 @@ from calibre.ebooks.rtf2xml import copy, check_brackets from calibre.ptempfile import better_mktemp -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -695,7 +694,7 @@ def color_func(self, pre, token, num): if num[-1] == ';': num = num[:-1] third_field = 'en' - num = unicode_type('%X' % int(num)) + num = '%X' % int(num) if len(num) != 2: num = "0" + num return 'cw<%s<%s<%s<%s\n' % (pre, token, third_field, num) @@ -732,7 +731,7 @@ def divide_num(self, numerator, denominator): return 0 num = '%0.2f' % round(numerator/denominator, 2) return num - string_num = unicode_type(num) + string_num = str(num) if string_num[-2:] == ".0": string_num = string_num[:-2] return string_num diff --git a/src/calibre/ebooks/rtf2xml/sections.py b/src/calibre/ebooks/rtf2xml/sections.py index 817a6d6a14..8d79d6d7a1 100644 --- a/src/calibre/ebooks/rtf2xml/sections.py +++ b/src/calibre/ebooks/rtf2xml/sections.py @@ -15,7 +15,6 @@ from calibre.ebooks.rtf2xml import copy from calibre.ptempfile import better_mktemp -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -276,8 +275,8 @@ def __write_section(self, line): my_string += 'mi%s' 'rtf-native' '0\n' - % (unicode_type(self.__section_num), unicode_type(self.__section_num)) + % (str(self.__section_num), str(self.__section_num)) ) self.__found_first_sec = 1 elif self.__token_info == 'tx%s' 'rtf-native' '0\n' - % (unicode_type(self.__section_num), unicode_type(self.__section_num)) + % (str(self.__section_num), str(self.__section_num)) ) self.__write_obj.write( 'cw%s' % unicode_type(num) + 'mi%s' % str(num) ) if self.__list_of_sec_values: keys = self.__list_of_sec_values[0].keys() @@ -473,7 +472,7 @@ def __print_field_sec_attributes(self): self.__list_of_sec_values = self.__list_of_sec_values[1:] self.__write_obj.write('0') self.__write_obj.write('rtf-native') - self.__write_obj.write('%s' % unicode_type(self.__section_num)) + self.__write_obj.write('%s' % str(self.__section_num)) self.__write_obj.write('\n') # Look here diff --git a/src/calibre/ebooks/rtf2xml/table.py b/src/calibre/ebooks/rtf2xml/table.py index f045e77b04..3b209d3ee0 100644 --- a/src/calibre/ebooks/rtf2xml/table.py +++ b/src/calibre/ebooks/rtf2xml/table.py @@ -15,7 +15,6 @@ from calibre.ebooks.rtf2xml import copy, border_parse from calibre.ptempfile import better_mktemp -from polyglot.builtins import unicode_type from . import open_for_read, open_for_write @@ -400,13 +399,13 @@ def __found_cell_position(self, line): left_position = float(left_position) width = new_cell_position - self.__last_cell_position - left_position # width = round(width, 2) - width = unicode_type('%.2f' % width) + width = '%.2f' % width self.__last_cell_position = new_cell_position widths_exists = self.__row_dict.get('widths') if widths_exists: - self.__row_dict['widths'] += ', %s' % unicode_type(width) + self.__row_dict['widths'] += ', %s' % str(width) else: - self.__row_dict['widths'] = unicode_type(width) + self.__row_dict['widths'] = str(width) self.__cell_list[-1]['width'] = width self.__cell_list.append({}) self.__cell_widths.append(width) diff --git a/src/calibre/ebooks/snb/snbfile.py b/src/calibre/ebooks/snb/snbfile.py index d76d719d0b..57566afe0b 100644 --- a/src/calibre/ebooks/snb/snbfile.py +++ b/src/calibre/ebooks/snb/snbfile.py @@ -8,7 +8,6 @@ import sys, struct, zlib, bz2, os from calibre import guess_type -from polyglot.builtins import unicode_type class FileStream: @@ -160,7 +159,7 @@ def AppendPlain(self, fileName, tdir): with open(os.path.join(tdir,fileName), 'rb') as data: f.fileBody = data.read() f.fileName = fileName.replace(os.sep, '/') - if isinstance(f.fileName, unicode_type): + if isinstance(f.fileName, str): f.fileName = f.fileName.encode("ascii", "ignore") self.files.append(f) @@ -171,7 +170,7 @@ def AppendBinary(self, fileName, tdir): with open(os.path.join(tdir,fileName), 'rb') as data: f.fileBody = data.read() f.fileName = fileName.replace(os.sep, '/') - if isinstance(f.fileName, unicode_type): + if isinstance(f.fileName, str): f.fileName = f.fileName.encode("ascii", "ignore") self.files.append(f) diff --git a/src/calibre/ebooks/snb/snbml.py b/src/calibre/ebooks/snb/snbml.py index 5186caddd4..e13877f7ad 100644 --- a/src/calibre/ebooks/snb/snbml.py +++ b/src/calibre/ebooks/snb/snbml.py @@ -13,7 +13,7 @@ import re from lxml import etree -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes def ProcessFileName(fileName): @@ -130,7 +130,7 @@ def mlize(self): else: prefix = '' etree.SubElement(bodyTree, "text").text = \ - etree.CDATA(unicode_type(prefix + line)) + etree.CDATA(str(prefix + line)) if self.opts and self.opts.snb_insert_empty_line: etree.SubElement(bodyTree, "text").text = \ etree.CDATA('') diff --git a/src/calibre/ebooks/textile/functions.py b/src/calibre/ebooks/textile/functions.py index 4abac7c89a..fc1cfb984a 100644 --- a/src/calibre/ebooks/textile/functions.py +++ b/src/calibre/ebooks/textile/functions.py @@ -65,7 +65,6 @@ import uuid from calibre.utils.smartypants import smartyPants -from polyglot.builtins import unicode_type from polyglot.urllib import urlopen, urlparse @@ -690,7 +689,7 @@ def footnoteRef(self, text): def footnoteID(self, match): id, t = match.groups() if id not in self.fn: - self.fn[id] = unicode_type(uuid.uuid4()) + self.fn[id] = str(uuid.uuid4()) fnid = self.fn[id] if not t: t = '' @@ -795,7 +794,7 @@ def relURL(self, url): return url def shelve(self, text): - id = unicode_type(uuid.uuid4()) + 'c' + id = str(uuid.uuid4()) + 'c' self.shelf[id] = text return id diff --git a/src/calibre/ebooks/txt/markdownml.py b/src/calibre/ebooks/txt/markdownml.py index b195170c87..7eaa293968 100644 --- a/src/calibre/ebooks/txt/markdownml.py +++ b/src/calibre/ebooks/txt/markdownml.py @@ -16,7 +16,7 @@ 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 unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes class MarkdownMLizer(OEB2HTML): @@ -227,7 +227,7 @@ def dump_text(self, elem, stylizer): text.append('+ ') elif li['name'] == 'ol': li['num'] += 1 - text.append(unicode_type(li['num']) + '. ') + text.append(str(li['num']) + '. ') # Process tags that contain text. if hasattr(elem, 'text') and elem.text: diff --git a/src/calibre/ebooks/txt/processor.py b/src/calibre/ebooks/txt/processor.py index e05adfbd79..a8da8d8c32 100644 --- a/src/calibre/ebooks/txt/processor.py +++ b/src/calibre/ebooks/txt/processor.py @@ -17,7 +17,7 @@ from calibre.ebooks.conversion.preprocess import DocAnalysis from calibre.utils.cleantext import clean_ascii_chars -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems HTML_TEMPLATE = '%s \n%s\n' @@ -62,7 +62,7 @@ def split_txt(txt, epub_split_size_kb=0): ''' # Takes care if there is no point to split if epub_split_size_kb > 0: - if isinstance(txt, unicode_type): + if isinstance(txt, str): txt = txt.encode('utf-8') if len(txt) > epub_split_size_kb * 1024: chunk_size = max(16, epub_split_size_kb - 32) * 1024 diff --git a/src/calibre/ebooks/unihandecode/pykakasi/jisyo.py b/src/calibre/ebooks/unihandecode/pykakasi/jisyo.py index a9feea295d..5b66e81a21 100644 --- a/src/calibre/ebooks/unihandecode/pykakasi/jisyo.py +++ b/src/calibre/ebooks/unihandecode/pykakasi/jisyo.py @@ -6,7 +6,6 @@ from zlib import decompress -from polyglot.builtins import unicode_type class jisyo : @@ -36,8 +35,8 @@ def __init__(self): P('localization/pykakasi/kanadict2.calibre_msgpack', data=True)) def load_jisyo(self, char): - if not isinstance(char, unicode_type): - char = unicode_type(char, 'utf-8') + if not isinstance(char, str): + char = str(char, 'utf-8') key = "%04x"%ord(char) try: # already exist? diff --git a/src/calibre/ebooks/unihandecode/unidecoder.py b/src/calibre/ebooks/unihandecode/unidecoder.py index 9c449b2aaf..cb9e9dc41e 100644 --- a/src/calibre/ebooks/unihandecode/unidecoder.py +++ b/src/calibre/ebooks/unihandecode/unidecoder.py @@ -63,7 +63,6 @@ import re from calibre.ebooks.unihandecode.unicodepoints import CODEPOINTS from calibre.ebooks.unihandecode.zhcodepoints import CODEPOINTS as HANCODES -from polyglot.builtins import unicode_type class Unidecoder: @@ -96,8 +95,8 @@ def code_group(self, character): Find what group character is a part of. ''' # Code groups within CODEPOINTS take the form 'xAB' - if not isinstance(character, unicode_type): - character = unicode_type(character, "utf-8") + if not isinstance(character, str): + character = str(character, "utf-8") return 'x%02x' % (ord(character) >> 8) def grouped_point(self, character): @@ -105,6 +104,6 @@ def grouped_point(self, character): Return the location the replacement character is in the list for a the group character is a part of. ''' - if not isinstance(character, unicode_type): - character = unicode_type(character, "utf-8") + if not isinstance(character, str): + character = str(character, "utf-8") return ord(character) & 255 diff --git a/src/calibre/gui2/__init__.py b/src/calibre/gui2/__init__.py index 935af43d64..62f181d659 100644 --- a/src/calibre/gui2/__init__.py +++ b/src/calibre/gui2/__init__.py @@ -38,7 +38,7 @@ from calibre.utils.file_type_icons import EXT_MAP from calibre.utils.localization import get_lang from polyglot import queue -from polyglot.builtins import iteritems, itervalues, string_or_bytes, unicode_type +from polyglot.builtins import iteritems, itervalues, string_or_bytes try: NO_URL_FORMATTING = QUrl.UrlFormattingOption.None_ @@ -422,7 +422,7 @@ def question_dialog(parent, title, msg, det_msg='', show_copy_button=False, from calibre.gui2.dialogs.message_box import MessageBox prefs = gui_prefs() - if not isinstance(skip_dialog_name, unicode_type): + if not isinstance(skip_dialog_name, str): skip_dialog_name = None try: auto_skip = set(prefs.get('questions_to_auto_skip', ())) @@ -642,7 +642,7 @@ def load_icon(self, fileinfo): if fileinfo.isDir(): key = 'dir' else: - ext = unicode_type(fileinfo.completeSuffix()).lower() + ext = str(fileinfo.completeSuffix()).lower() key = self.key_from_ext(ext) return self.cached_icon(key) @@ -768,7 +768,7 @@ class Translator(QTranslator): def translate(self, *args, **kwargs): try: - src = unicode_type(args[1]) + src = str(args[1]) except: return '' t = _ @@ -799,7 +799,7 @@ def load_builtin_fonts(): fid = QFontDatabase.addApplicationFontFromData(s.read()) if fid > -1: fam = QFontDatabase.applicationFontFamilies(fid) - fam = set(map(unicode_type, fam)) + fam = set(map(str, fam)) if 'calibre Symbols' in fam: _rating_font = 'calibre Symbols' @@ -879,7 +879,7 @@ def __init__(self, args, force_calibre_style=False, override_program_name=None, if iswindows: self.windows_app_uid = None if windows_app_uid: - windows_app_uid = unicode_type(windows_app_uid) + windows_app_uid = str(windows_app_uid) if set_app_uid(windows_app_uid): self.windows_app_uid = windows_app_uid self.file_event_hook = None @@ -892,7 +892,7 @@ def __init__(self, args, force_calibre_style=False, override_program_name=None, args = sys.argv[:1] args.extend(['-platformpluginpath', plugins_loc, '-platform', 'headless']) self.headless = headless - qargs = [i.encode('utf-8') if isinstance(i, unicode_type) else i for i in args] + qargs = [i.encode('utf-8') if isinstance(i, str) else i for i in args] from calibre_extensions import progress_indicator self.pi = progress_indicator if not ismacos and not headless: @@ -950,7 +950,7 @@ def __init__(self, args, force_calibre_style=False, override_program_name=None, self.line_height = max(12, QFontMetrics(self.font()).lineSpacing()) dl = QLocale(get_lang()) - if unicode_type(dl.bcp47Name()) != 'C': + if str(dl.bcp47Name()) != 'C': QLocale.setDefault(dl) global gui_thread, qt_app gui_thread = QThread.currentThread() @@ -1175,7 +1175,7 @@ def event(self, e): self._file_open_paths.append(url) QTimer.singleShot(1000, self._send_file_open_events) return True - path = unicode_type(e.file()) + path = str(e.file()) if os.access(path, os.R_OK): with self._file_open_lock: self._file_open_paths.append(path) @@ -1415,7 +1415,7 @@ def remove_middle(x): chomp = {'middle':remove_middle, 'left':lambda x:(ellipsis + x[delta:]), 'right':lambda x:(x[:-delta] + ellipsis)}[pos] while len(text) > delta and fm.width(text) > width: text = chomp(text) - return unicode_type(text) + return str(text) def find_forms(srcdir): @@ -1506,7 +1506,7 @@ def set_app_uid(val): AppUserModelID.argtypes = [wintypes.LPCWSTR] AppUserModelID.restype = HRESULT try: - AppUserModelID(unicode_type(val)) + AppUserModelID(str(val)) except Exception as err: prints('Failed to set app uid with error:', as_unicode(err)) return False @@ -1516,7 +1516,7 @@ def set_app_uid(val): def add_to_recent_docs(path): from calibre_extensions import winutil app = QApplication.instance() - winutil.add_to_recent_docs(unicode_type(path), app.windows_app_uid) + winutil.add_to_recent_docs(str(path), app.windows_app_uid) def windows_is_system_dark_mode_enabled(): diff --git a/src/calibre/gui2/actions/__init__.py b/src/calibre/gui2/actions/__init__.py index 44bd894c77..194df43693 100644 --- a/src/calibre/gui2/actions/__init__.py +++ b/src/calibre/gui2/actions/__init__.py @@ -16,7 +16,7 @@ from calibre.constants import ismacos from calibre.gui2 import Dispatcher from calibre.gui2.keyboard import NameConflict -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes def menu_action_unique_name(plugin, unique_name): @@ -164,7 +164,7 @@ def create_action(self, spec=None, attr='qaction', shortcut_name=None, persist_s action = QAction(text, self.gui) if attr == 'qaction': if hasattr(self.action_menu_clone_qaction, 'rstrip'): - mt = unicode_type(self.action_menu_clone_qaction) + mt = str(self.action_menu_clone_qaction) else: mt = action.text() self.menuless_qaction = ma = QAction(action.icon(), mt, self.gui) @@ -183,7 +183,7 @@ def create_action(self, spec=None, attr='qaction', shortcut_name=None, persist_s keys = ((shortcut,) if isinstance(shortcut, string_or_bytes) else tuple(shortcut)) if shortcut_name is None and spec[0]: - shortcut_name = unicode_type(spec[0]) + shortcut_name = str(spec[0]) if shortcut_name and self.action_spec[0] and not ( attr == 'qaction' and self.popup_type == QToolButton.ToolButtonPopupMode.InstantPopup): @@ -195,7 +195,7 @@ def create_action(self, spec=None, attr='qaction', shortcut_name=None, persist_s persist_shortcut=persist_shortcut) except NameConflict as e: try: - prints(unicode_type(e)) + prints(str(e)) except: pass shortcut_action.setShortcuts([QKeySequence(key, @@ -250,7 +250,7 @@ def create_menu_action(self, menu, unique_name, text, icon=None, shortcut=None, ''' if shortcut_name is None: - shortcut_name = unicode_type(text) + shortcut_name = str(text) ac = menu.addAction(text) if icon is not None: if not isinstance(icon, QIcon): diff --git a/src/calibre/gui2/actions/choose_library.py b/src/calibre/gui2/actions/choose_library.py index b1d191936a..b71332e666 100644 --- a/src/calibre/gui2/actions/choose_library.py +++ b/src/calibre/gui2/actions/choose_library.py @@ -20,7 +20,6 @@ from calibre.gui2 import (gprefs, warning_dialog, Dispatcher, error_dialog, question_dialog, info_dialog, open_local_file, choose_dir) from calibre.gui2.actions import InterfaceAction -from polyglot.builtins import unicode_type def db_class(): @@ -144,7 +143,7 @@ def forget_library(self): self.stats.remove(self.location) def accept(self): - newloc = unicode_type(self.loc.text()) + newloc = str(self.loc.text()) if not db_class().exists_at(newloc): error_dialog(self, _('No library found'), _('No existing calibre library found at %s')%newloc, @@ -269,7 +268,7 @@ def genesis(self): for i in range(5): ac = self.create_action(spec=('', None, None, None), attr='switch_action%d'%i) - ac.setObjectName(unicode_type(i)) + ac.setObjectName(str(i)) self.switch_actions.append(ac) ac.setVisible(False) connect_lambda(ac.triggered, self, lambda self: @@ -474,7 +473,7 @@ def rename_requested(self, name, location): 'Choose a new name for the library %s. ')%name + '

'+_( 'Note that the actual library folder will be renamed.'), text=old_name) - newname = sanitize_file_name(unicode_type(newname)) + newname = sanitize_file_name(str(newname)) if not ok or not newname or newname == old_name: return newloc = os.path.join(base, newname) diff --git a/src/calibre/gui2/actions/copy_to_library.py b/src/calibre/gui2/actions/copy_to_library.py index 9407901ac7..f0c6c25c69 100644 --- a/src/calibre/gui2/actions/copy_to_library.py +++ b/src/calibre/gui2/actions/copy_to_library.py @@ -27,7 +27,7 @@ from calibre.utils.config import prefs from calibre.utils.icu import sort_key, numeric_sort_key from calibre.db.copy_to_library import copy_one_book -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues def ask_about_cc_mismatch(gui, db, newdb, missing_cols, incompatible_cols): # {{{ @@ -134,7 +134,7 @@ def run(self): except Exception as err: import traceback try: - err = unicode_type(err) + err = str(err) except: err = repr(err) self.error = (err, traceback.format_exc()) @@ -263,7 +263,7 @@ def browse(self): @property def args(self): - return (unicode_type(self.le.text()), self.delete_after_copy) + return (str(self.le.text()), self.delete_after_copy) # }}} @@ -301,7 +301,7 @@ def __init__(self, parent, duplicates, loc): self.resize(600, 400) def copy_to_clipboard(self): - items = [('✓' if item.checkState() == Qt.CheckState.Checked else '✗') + ' ' + unicode_type(item.text()) + items = [('✓' if item.checkState() == Qt.CheckState.Checked else '✗') + ' ' + str(item.text()) for item in self.items] QApplication.clipboard().setText('\n'.join(items)) diff --git a/src/calibre/gui2/actions/device.py b/src/calibre/gui2/actions/device.py index c2cfcad581..90e2936ef9 100644 --- a/src/calibre/gui2/actions/device.py +++ b/src/calibre/gui2/actions/device.py @@ -13,7 +13,6 @@ from calibre.gui2.dialogs.smartdevice import SmartdeviceDialog from calibre.utils.icu import primary_sort_key from calibre.utils.smtp import config as email_config -from polyglot.builtins import unicode_type class ShareConnMenu(QMenu): # {{{ @@ -56,7 +55,7 @@ def __init__(self, parent=None): gr = ConnectShareAction.action_spec[0] for attr in ('folder', ): ac = getattr(self, 'connect_to_%s_action'%attr) - r(prefix + attr, unicode_type(ac.text()), action=ac, + r(prefix + attr, str(ac.text()), action=ac, group=gr) r(prefix+' content server', _('Start/stop Content server'), action=self.toggle_server_action, group=gr) diff --git a/src/calibre/gui2/actions/edit_metadata.py b/src/calibre/gui2/actions/edit_metadata.py index ba0dd5c0d2..edadd5dc49 100644 --- a/src/calibre/gui2/actions/edit_metadata.py +++ b/src/calibre/gui2/actions/edit_metadata.py @@ -30,7 +30,7 @@ from calibre.utils.config import tweaks from calibre.utils.date import is_date_undefined from calibre.utils.icu import sort_key -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class EditMetadataAction(InterfaceAction): @@ -173,7 +173,7 @@ def copy_metadata(self): book_id = db.id(rows[0].row()) mi = db.new_api.get_metadata(book_id) md = QMimeData() - md.setText(unicode_type(mi)) + md.setText(str(mi)) md.setData('application/calibre-book-metadata', bytearray(metadata_to_opf(mi, default_lang='und'))) img = db.new_api.cover(book_id, as_image=True) if img: @@ -702,7 +702,7 @@ def is_null_date(x): if not dest_mi.comments: dest_mi.comments = src_mi.comments else: - dest_mi.comments = unicode_type(dest_mi.comments) + '\n\n' + unicode_type(src_mi.comments) + dest_mi.comments = str(dest_mi.comments) + '\n\n' + str(src_mi.comments) if src_mi.title and (not dest_mi.title or dest_mi.title == _('Unknown')): dest_mi.title = src_mi.title if (src_mi.authors and src_mi.authors[0] != _('Unknown')) and (not dest_mi.authors or dest_mi.authors[0] == _('Unknown')): @@ -755,7 +755,7 @@ def is_null_date(x): if not dest_value: db.set_custom(dest_id, src_value, num=colnum) else: - dest_value = unicode_type(dest_value) + '\n\n' + unicode_type(src_value) + dest_value = str(dest_value) + '\n\n' + str(src_value) db.set_custom(dest_id, dest_value, num=colnum) if (dt in {'bool', 'int', 'float', 'rating', 'datetime'} and dest_value is None): db.set_custom(dest_id, src_value, num=colnum) @@ -781,7 +781,7 @@ def edit_device_collections(self, view, oncard=None): to_rename = d.to_rename # dict of new text to old ids to_delete = d.to_delete # list of ids for old_id, new_name in iteritems(to_rename): - model.rename_collection(old_id, new_name=unicode_type(new_name)) + model.rename_collection(old_id, new_name=str(new_name)) for item in to_delete: model.delete_collection_using_id(item) self.gui.upload_collections(model.db, view=view, oncard=oncard) diff --git a/src/calibre/gui2/actions/mark_books.py b/src/calibre/gui2/actions/mark_books.py index 9146386ce0..15464d093c 100644 --- a/src/calibre/gui2/actions/mark_books.py +++ b/src/calibre/gui2/actions/mark_books.py @@ -11,7 +11,6 @@ from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction -from polyglot.builtins import unicode_type class MarkBooksAction(InterfaceAction): @@ -120,7 +119,7 @@ def show_marked(self): def clear_all_marked(self): self.gui.current_db.data.set_marked_ids(()) - if unicode_type(self.gui.search.text()).startswith('marked:'): + if str(self.gui.search.text()).startswith('marked:'): self.gui.search.set_search_string('') def mark_field(self, field, add): diff --git a/src/calibre/gui2/actions/polish.py b/src/calibre/gui2/actions/polish.py index 7f47e11397..4d6c545bf6 100644 --- a/src/calibre/gui2/actions/polish.py +++ b/src/calibre/gui2/actions/polish.py @@ -9,7 +9,7 @@ import os, weakref, shutil, textwrap from collections import OrderedDict from functools import partial -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from qt.core import (QDialog, QGridLayout, QIcon, QCheckBox, QLabel, QFrame, QApplication, QDialogButtonBox, Qt, QSize, QSpacerItem, @@ -159,7 +159,7 @@ def save_settings(self): name, ok = QInputDialog.getText(self, _('Choose name'), _('Choose a name for these settings')) if ok: - name = unicode_type(name).strip() + name = str(name).strip() if name: settings = {ac:getattr(self, 'opt_'+ac).isChecked() for ac in self.all_actions} @@ -198,7 +198,7 @@ def option_toggled(self, name, state): self.help_label.setText(self.help_text[name]) def help_link_activated(self, link): - link = unicode_type(link)[1:] + link = str(link)[1:] self.help_label.setText(self.help_text[link]) @property @@ -272,7 +272,7 @@ def do_one(self): QTimer.singleShot(0, self.do_one) def do_book(self, num, book_id, formats): - base = os.path.join(self.tdir, unicode_type(book_id)) + base = os.path.join(self.tdir, str(book_id)) os.mkdir(base) db = self.db() opf = os.path.join(base, 'metadata.opf') diff --git a/src/calibre/gui2/actions/toc_edit.py b/src/calibre/gui2/actions/toc_edit.py index b0ebee7aec..69265ac540 100644 --- a/src/calibre/gui2/actions/toc_edit.py +++ b/src/calibre/gui2/actions/toc_edit.py @@ -15,7 +15,7 @@ from calibre.gui2 import error_dialog, gprefs, question_dialog from calibre.gui2.actions import InterfaceAction from calibre.utils.monotonic import monotonic -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems SUPPORTED = {'EPUB', 'AZW3'} @@ -56,7 +56,7 @@ def do_all(self): def formats(self): for b in self.buttons: if b.isChecked(): - yield unicode_type(b.text())[1:] + yield str(b.text())[1:] @formats.setter def formats(self, formats): diff --git a/src/calibre/gui2/actions/unpack_book.py b/src/calibre/gui2/actions/unpack_book.py index 6b646aa465..dbea570b46 100644 --- a/src/calibre/gui2/actions/unpack_book.py +++ b/src/calibre/gui2/actions/unpack_book.py @@ -18,7 +18,6 @@ from calibre.ptempfile import (PersistentTemporaryDirectory, PersistentTemporaryFile) from calibre.utils.config import prefs, tweaks -from polyglot.builtins import unicode_type class UnpackBook(QDialog): @@ -36,7 +35,7 @@ def __init__(self, parent, book_id, fmts, db): index_is_id=True)) button = self.fmt_choice_buttons[0] - button_map = {unicode_type(x.text()):x for x in self.fmt_choice_buttons} + button_map = {str(x.text()):x for x in self.fmt_choice_buttons} of = prefs['output_format'].upper() df = tweaks.get('default_tweak_format', None) lf = gprefs.get('last_tweak_format', None) @@ -283,7 +282,7 @@ def db(self): def current_format(self): for b in self.fmt_choice_buttons: if b.isChecked(): - return unicode_type(b.text()) + return str(b.text()) class UnpackBookAction(InterfaceAction): diff --git a/src/calibre/gui2/actions/view.py b/src/calibre/gui2/actions/view.py index 2f067743a8..189459a778 100644 --- a/src/calibre/gui2/actions/view.py +++ b/src/calibre/gui2/actions/view.py @@ -21,7 +21,7 @@ from calibre.gui2.dialogs.choose_format import ChooseFormatDialog from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.config import prefs, tweaks -from polyglot.builtins import as_bytes, unicode_type +from polyglot.builtins import as_bytes def preferred_format(formats): @@ -180,7 +180,7 @@ def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True, calibr ext = name.rpartition('.')[-1] if ext: try: - prog = winutil.file_association(unicode_type('.' + ext)) + prog = winutil.file_association(str('.' + ext)) except Exception: prog = None if prog and prog.lower().endswith('calibre.exe'): diff --git a/src/calibre/gui2/add.py b/src/calibre/gui2/add.py index 818c5b0d5e..0e4211991d 100644 --- a/src/calibre/gui2/add.py +++ b/src/calibre/gui2/add.py @@ -33,7 +33,7 @@ from calibre.utils.config import prefs from calibre.utils.filenames import make_long_path_useable from calibre.utils.ipc.pool import Failure, Pool -from polyglot.builtins import iteritems, string_or_bytes, unicode_type +from polyglot.builtins import iteritems, string_or_bytes from polyglot.queue import Empty @@ -180,7 +180,7 @@ def find_files(root): self.file_groups[len(self.file_groups)] = files else: def find_files(root): - if isinstance(root, unicode_type): + if isinstance(root, str): root = root.encode(filesystem_encoding) for dirpath, dirnames, filenames in os.walk(root): try: @@ -314,7 +314,7 @@ def monitor_pool(self): except Failure as err: error_dialog(self.pd, _('Cannot add books'), _( 'Failed to add some books, click "Show details" for more information.'), - det_msg=unicode_type(err.failure_message) + '\n' + unicode_type(err.details), show=True) + det_msg=str(err.failure_message) + '\n' + str(err.details), show=True) self.pd.canceled = True else: # All tasks completed diff --git a/src/calibre/gui2/add_filters.py b/src/calibre/gui2/add_filters.py index e51091ee4e..a667501979 100644 --- a/src/calibre/gui2/add_filters.py +++ b/src/calibre/gui2/add_filters.py @@ -4,7 +4,6 @@ from collections import OrderedDict -from polyglot.builtins import unicode_type from calibre.db.adding import compile_glob, filter_filename, compile_rule from calibre.gui2 import elided_text, Application, error_dialog @@ -64,12 +63,12 @@ def rule(self): def rule(self, rule): def sc(name): c = getattr(self, name) - idx = c.findData(unicode_type(rule.get(name, ''))) + idx = c.findData(str(rule.get(name, ''))) if idx < 0: idx = 0 c.setCurrentIndex(idx) sc('action'), sc('match_type') - self.query.setText(unicode_type(rule.get('query', '')).strip()) + self.query.setText(str(rule.get('query', '')).strip()) def validate(self): ans = super(RuleEdit, self).validate() diff --git a/src/calibre/gui2/author_mapper.py b/src/calibre/gui2/author_mapper.py index 322cc415b3..3191a76237 100644 --- a/src/calibre/gui2/author_mapper.py +++ b/src/calibre/gui2/author_mapper.py @@ -14,7 +14,6 @@ Tester as TesterBase ) from calibre.utils.config import JSONConfig -from polyglot.builtins import unicode_type author_maps = JSONConfig('author-mapping-rules') @@ -66,13 +65,13 @@ def rule(self): def rule(self, rule): def sc(name): c = getattr(self, name) - idx = c.findData(unicode_type(rule.get(name, ''))) + idx = c.findData(str(rule.get(name, ''))) if idx < 0: idx = 0 c.setCurrentIndex(idx) sc('match_type'), sc('action') - self.query.setText(unicode_type(rule.get('query', '')).strip()) - self.replace.setText(unicode_type(rule.get('replace', '')).strip()) + self.query.setText(str(rule.get('query', '')).strip()) + self.replace.setText(str(rule.get('replace', '')).strip()) class RuleEditDialog(RuleEditDialogBase): diff --git a/src/calibre/gui2/bars.py b/src/calibre/gui2/bars.py index 16b1039d3e..406996803d 100644 --- a/src/calibre/gui2/bars.py +++ b/src/calibre/gui2/bars.py @@ -14,7 +14,7 @@ from calibre.constants import ismacos from calibre.gui2 import gprefs, native_menubar_defaults, config from calibre.gui2.throbber import ThrobbingButton -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues class RevealBar(QWidget): # {{{ @@ -300,7 +300,7 @@ def dropEvent(self, event): mime = 'application/calibre+from_device' if md.hasFormat(mime): - paths = [unicode_type(u.toLocalFile()) for u in md.urls()] + paths = [str(u.toLocalFile()) for u in md.urls()] if paths: self.gui.iactions['Add Books'].add_books_from_device( self.gui.current_view(), paths=paths) diff --git a/src/calibre/gui2/book_details.py b/src/calibre/gui2/book_details.py index 1325a00771..144c153cc9 100644 --- a/src/calibre/gui2/book_details.py +++ b/src/calibre/gui2/book_details.py @@ -36,7 +36,6 @@ from calibre.utils.localization import is_rtl, langnames_to_langcodes from calibre.utils.serialize import json_loads from polyglot.binary import from_hex_bytes -from polyglot.builtins import unicode_type InternetSearch = namedtuple('InternetSearch', 'author where') @@ -59,7 +58,7 @@ def css(reset=False): del css.ans if not hasattr(css, 'ans'): val = P('templates/book_details.css', data=True).decode('utf-8') - css.ans = re.sub(unicode_type(r'/\*.*?\*/'), '', val, flags=re.DOTALL) + css.ans = re.sub(r'/\*.*?\*/', '', val, flags=re.DOTALL) return css.ans @@ -180,7 +179,7 @@ def color_to_string(col): if col.isValid(): col = col.toRgb() if col.isValid(): - ans = unicode_type(col.name()) + ans = str(col.name()) return ans templ = '''\ @@ -789,9 +788,9 @@ def manage_action_triggered(self): self.manage_category.emit(*self.manage_action.current_fmt) def link_activated(self, link): - if unicode_type(link.scheme()) in ('http', 'https'): + if str(link.scheme()) in ('http', 'https'): return safe_open_url(link) - link = unicode_type(link.toString(NO_URL_FORMATTING)) + link = str(link.toString(NO_URL_FORMATTING)) self.link_clicked.emit(link) def show_data(self, mi): diff --git a/src/calibre/gui2/catalog/catalog_bibtex.py b/src/calibre/gui2/catalog/catalog_bibtex.py index 4583091e66..0932cdfecf 100644 --- a/src/calibre/gui2/catalog/catalog_bibtex.py +++ b/src/calibre/gui2/catalog/catalog_bibtex.py @@ -11,7 +11,6 @@ from calibre.gui2 import gprefs from calibre.gui2.catalog.catalog_bibtex_ui import Ui_Form -from polyglot.builtins import unicode_type class PluginWidget(QWidget, Ui_Form): @@ -51,7 +50,7 @@ def initialize(self, name, db): # not working properly to update # Restore the activated db_fields from last use for x in range(self.db_fields.count()): item = self.db_fields.item(x) - item.setSelected(unicode_type(item.text()) in fields) + item.setSelected(str(item.text()) in fields) self.bibfile_enc.clear() self.bibfile_enc.addItems(['utf-8', 'cp1252', 'ascii/LaTeX']) self.bibfile_enctag.clear() @@ -76,12 +75,12 @@ def options(self): for x in range(self.db_fields.count()): item = self.db_fields.item(x) if item.isSelected(): - fields.append(unicode_type(item.text())) + fields.append(str(item.text())) gprefs.set(self.name+'_db_fields', fields) # Dictionary currently activated fields if len(self.db_fields.selectedItems()): - opts_dict = {'fields':[unicode_type(i.text()) for i in self.db_fields.selectedItems()]} + opts_dict = {'fields':[str(i.text()) for i in self.db_fields.selectedItems()]} else: opts_dict = {'fields':['all']} @@ -94,7 +93,7 @@ def options(self): elif opt[0] in ['impcit', 'addfiles'] : opt_value = getattr(self, opt[0]).isChecked() else : - opt_value = unicode_type(getattr(self, opt[0]).text()) + opt_value = str(getattr(self, opt[0]).text()) gprefs.set(self.name + '_' + opt[0], opt_value) opts_dict[opt[0]] = opt_value diff --git a/src/calibre/gui2/catalog/catalog_csv_xml.py b/src/calibre/gui2/catalog/catalog_csv_xml.py index 1838e526dd..c18b9a3c3b 100644 --- a/src/calibre/gui2/catalog/catalog_csv_xml.py +++ b/src/calibre/gui2/catalog/catalog_csv_xml.py @@ -11,7 +11,6 @@ from calibre.constants import ismacos from calibre.gui2 import gprefs from calibre.gui2.ui import get_gui -from polyglot.builtins import unicode_type def get_saved_field_data(name, all_fields): @@ -87,16 +86,16 @@ def key(x): # Restore the activated fields from last use for x in range(self.db_fields.count()): item = self.db_fields.item(x) - item.setCheckState(Qt.CheckState.Checked if unicode_type(item.data(Qt.ItemDataRole.UserRole)) in fields else Qt.CheckState.Unchecked) + item.setCheckState(Qt.CheckState.Checked if str(item.data(Qt.ItemDataRole.UserRole)) in fields else Qt.CheckState.Unchecked) def options(self): # Save the currently activated fields fields, all_fields = [], [] for x in range(self.db_fields.count()): item = self.db_fields.item(x) - all_fields.append(unicode_type(item.data(Qt.ItemDataRole.UserRole))) + all_fields.append(str(item.data(Qt.ItemDataRole.UserRole))) if item.checkState() == Qt.CheckState.Checked: - fields.append(unicode_type(item.data(Qt.ItemDataRole.UserRole))) + fields.append(str(item.data(Qt.ItemDataRole.UserRole))) set_saved_field_data(self.name, fields, {x:i for i, x in enumerate(all_fields)}) # Return a dictionary with current options for this widget diff --git a/src/calibre/gui2/catalog/catalog_epub_mobi.py b/src/calibre/gui2/catalog/catalog_epub_mobi.py index ad99cee609..fe83a86eb1 100644 --- a/src/calibre/gui2/catalog/catalog_epub_mobi.py +++ b/src/calibre/gui2/catalog/catalog_epub_mobi.py @@ -15,7 +15,7 @@ from calibre.utils.config import JSONConfig from calibre.utils.icu import sort_key from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import native_string_type, unicode_type +from polyglot.builtins import native_string_type from .catalog_epub_mobi_ui import Ui_Form from qt.core import (Qt, QAbstractItemView, QCheckBox, QComboBox, @@ -199,7 +199,7 @@ def _truncated_results(excluded_tags, limit=180): results = _('No genres will be excluded') - regex = unicode_type(getattr(self, 'exclude_genre').text()).strip() + regex = str(getattr(self, 'exclude_genre').text()).strip() if not regex: self.exclude_genre_results.clear() self.exclude_genre_results.setText(results) @@ -274,7 +274,7 @@ def genre_source_field_changed(self,new_index): new_source = self.genre_source_field.currentText() self.genre_source_field_name = new_source if new_source != _('Tags'): - genre_source_spec = self.genre_source_fields[unicode_type(new_source)] + genre_source_spec = self.genre_source_fields[str(new_source)] self.genre_source_field_name = genre_source_spec['field'] self.exclude_genre_changed() @@ -294,7 +294,7 @@ def header_note_source_field_changed(self,new_index): new_source = self.header_note_source_field.currentText() self.header_note_source_field_name = new_source if new_source: - header_note_source_spec = self.header_note_source_fields[unicode_type(new_source)] + header_note_source_spec = self.header_note_source_fields[str(new_source)] self.header_note_source_field_name = header_note_source_spec['field'] def initialize(self, name, db): @@ -335,7 +335,7 @@ def initialize(self, name, db): c_name, c_def, c_type = opt opt_value = gprefs.get(self.name + '_' + c_name, c_def) if c_type in ['check_box']: - getattr(self, c_name).setChecked(eval(unicode_type(opt_value))) + getattr(self, c_name).setChecked(eval(str(opt_value))) getattr(self, c_name).clicked.connect(partial(self.settings_changed, c_name)) elif c_type in ['combo_box']: if opt_value is None: @@ -382,21 +382,21 @@ def initialize(self, name, db): # Init self.merge_source_field_name self.merge_source_field_name = '' - cs = unicode_type(self.merge_source_field.currentText()) + cs = str(self.merge_source_field.currentText()) if cs: merge_source_spec = self.merge_source_fields[cs] self.merge_source_field_name = merge_source_spec['field'] # Init self.header_note_source_field_name self.header_note_source_field_name = '' - cs = unicode_type(self.header_note_source_field.currentText()) + cs = str(self.header_note_source_field.currentText()) if cs: header_note_source_spec = self.header_note_source_fields[cs] self.header_note_source_field_name = header_note_source_spec['field'] # Init self.genre_source_field_name self.genre_source_field_name = _('Tags') - cs = unicode_type(self.genre_source_field.currentText()) + cs = str(self.genre_source_field.currentText()) if cs != _('Tags'): genre_source_spec = self.genre_source_fields[cs] self.genre_source_field_name = genre_source_spec['field'] @@ -430,7 +430,7 @@ def merge_source_field_changed(self,new_index): new_source = self.merge_source_field.currentText() self.merge_source_field_name = new_source if new_source: - merge_source_spec = self.merge_source_fields[unicode_type(new_source)] + merge_source_spec = self.merge_source_fields[str(new_source)] self.merge_source_field_name = merge_source_spec['field'] if not self.merge_before.isChecked() and not self.merge_after.isChecked(): self.merge_after.setChecked(True) @@ -465,11 +465,11 @@ def options(self): if c_type in ['check_box', 'radio_button']: opt_value = getattr(self, c_name).isChecked() elif c_type in ['combo_box']: - opt_value = unicode_type(getattr(self,c_name).currentText()).strip() + opt_value = str(getattr(self,c_name).currentText()).strip() elif c_type in ['line_edit']: - opt_value = unicode_type(getattr(self, c_name).text()).strip() + opt_value = str(getattr(self, c_name).text()).strip() elif c_type in ['spin_box']: - opt_value = unicode_type(getattr(self, c_name).value()) + opt_value = str(getattr(self, c_name).value()) elif c_type in ['table_widget']: if c_name == 'prefix_rules_tw': opt_value = self.prefix_rules_table.get_data() @@ -497,21 +497,21 @@ def options(self): # Init self.merge_source_field_name self.merge_source_field_name = '' - cs = unicode_type(self.merge_source_field.currentText()) + cs = str(self.merge_source_field.currentText()) if cs and cs in self.merge_source_fields: merge_source_spec = self.merge_source_fields[cs] self.merge_source_field_name = merge_source_spec['field'] # Init self.header_note_source_field_name self.header_note_source_field_name = '' - cs = unicode_type(self.header_note_source_field.currentText()) + cs = str(self.header_note_source_field.currentText()) if cs and cs in self.header_note_source_fields: header_note_source_spec = self.header_note_source_fields[cs] self.header_note_source_field_name = header_note_source_spec['field'] # Init self.genre_source_field_name self.genre_source_field_name = _('Tags') - cs = unicode_type(self.genre_source_field.currentText()) + cs = str(self.genre_source_field.currentText()) if cs != _('Tags') and cs and cs in self.genre_source_fields: genre_source_spec = self.genre_source_fields[cs] self.genre_source_field_name = genre_source_spec['field'] @@ -638,9 +638,9 @@ def preset_change(self, item_name): else: continue if c_type in ['check_box']: - getattr(self, c_name).setChecked(eval(unicode_type(opt_value))) + getattr(self, c_name).setChecked(eval(str(opt_value))) if c_name == 'generate_genres': - self.genre_source_field.setEnabled(eval(unicode_type(opt_value))) + self.genre_source_field.setEnabled(eval(str(opt_value))) elif c_type in ['combo_box']: if opt_value is None: index = 0 @@ -701,7 +701,7 @@ def preset_remove(self): return item_id = self.preset_field.currentIndex() - item_name = unicode_type(self.preset_field.currentText()) + item_name = str(self.preset_field.currentText()) self.preset_field.blockSignals(True) self.preset_field.removeItem(item_id) @@ -729,7 +729,7 @@ def preset_save(self): error_dialog(self, _("Save catalog preset"), _("You must provide a name."), show=True) new = True - name = unicode_type(name) + name = str(name) if name in self.presets.keys(): if not question_dialog(self, _("Save catalog preset"), _("That saved preset already exists and will be overwritten. " @@ -753,11 +753,11 @@ def preset_save(self): elif c_type in ['combo_box']: if c_name == 'preset_field': continue - opt_value = unicode_type(getattr(self,c_name).currentText()).strip() + opt_value = str(getattr(self,c_name).currentText()).strip() elif c_type in ['line_edit']: - opt_value = unicode_type(getattr(self, c_name).text()).strip() + opt_value = str(getattr(self, c_name).text()).strip() elif c_type in ['spin_box']: - opt_value = unicode_type(getattr(self, c_name).value()) + opt_value = str(getattr(self, c_name).value()) elif c_type in ['table_widget']: if c_name == 'prefix_rules_tw': opt_value = self.prefix_rules_table.get_data() @@ -786,8 +786,8 @@ def preset_save(self): preset['merge_comments_rule'] = "%s:%s:%s" % \ (self.merge_source_field_name, checked, include_hr) - preset['header_note_source_field'] = unicode_type(self.header_note_source_field.currentText()) - preset['genre_source_field'] = unicode_type(self.genre_source_field.currentText()) + preset['header_note_source_field'] = str(self.header_note_source_field.currentText()) + preset['genre_source_field'] = str(self.genre_source_field.currentText()) # Append the current output profile try: @@ -998,7 +998,7 @@ def delete_row(self): first = rows[0].row() + 1 last = rows[-1].row() + 1 - first_rule_name = unicode_type(self.cellWidget(first-1,self.COLUMNS['NAME']['ordinal']).text()).strip() + first_rule_name = str(self.cellWidget(first-1,self.COLUMNS['NAME']['ordinal']).text()).strip() message = _("Are you sure you want to delete '%s'?") % (first_rule_name) if len(rows) > 1: message = _('Are you sure you want to delete rules #%(first)d-%(last)d?') % dict(first=first, last=last) @@ -1153,15 +1153,15 @@ def source_index_changed(self, combo, row, pattern=''): elif source_field == _('Tags'): values = sorted(self.db.all_tags(), key=sort_key) else: - if self.eligible_custom_fields[unicode_type(source_field)]['datatype'] in ['enumeration', 'text']: + if self.eligible_custom_fields[str(source_field)]['datatype'] in ['enumeration', 'text']: values = self.db.all_custom(self.db.field_metadata.key_to_label( - self.eligible_custom_fields[unicode_type(source_field)]['field'])) + self.eligible_custom_fields[str(source_field)]['field'])) values = sorted(values, key=sort_key) - elif self.eligible_custom_fields[unicode_type(source_field)]['datatype'] in ['bool']: + elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['bool']: values = [_('True'),_('False'),_('unspecified')] - elif self.eligible_custom_fields[unicode_type(source_field)]['datatype'] in ['composite']: + elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['composite']: values = [_('any value'),_('unspecified')] - elif self.eligible_custom_fields[unicode_type(source_field)]['datatype'] in ['datetime']: + elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['datetime']: values = [_('any date'),_('unspecified')] values_combo = ComboBox(self, values, pattern) @@ -1215,9 +1215,9 @@ def convert_row_to_data(self, row): data = self.create_blank_row_data() data['ordinal'] = row data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.CheckState.Checked - data['name'] = unicode_type(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip() - data['field'] = unicode_type(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip() - data['pattern'] = unicode_type(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip() + data['name'] = str(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip() + data['field'] = str(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip() + data['pattern'] = str(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip() return data def create_blank_row_data(self): @@ -1309,10 +1309,10 @@ def convert_row_to_data(self, row): data = self.create_blank_row_data() data['ordinal'] = row data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.CheckState.Checked - data['name'] = unicode_type(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip() - data['prefix'] = unicode_type(self.cellWidget(row,self.COLUMNS['PREFIX']['ordinal']).currentText()).strip() - data['field'] = unicode_type(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip() - data['pattern'] = unicode_type(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip() + data['name'] = str(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip() + data['prefix'] = str(self.cellWidget(row,self.COLUMNS['PREFIX']['ordinal']).currentText()).strip() + data['field'] = str(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip() + data['pattern'] = str(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip() return data def create_blank_row_data(self): diff --git a/src/calibre/gui2/comments_editor.py b/src/calibre/gui2/comments_editor.py index c7d9a14a4b..43a266e833 100644 --- a/src/calibre/gui2/comments_editor.py +++ b/src/calibre/gui2/comments_editor.py @@ -31,7 +31,7 @@ from calibre.utils.cleantext import clean_xml_chars from calibre.utils.config import tweaks from calibre.utils.imghdr import what -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues # Cleanup Qt markup {{{ @@ -602,7 +602,7 @@ def do_insert_link(self, *args): return url = self.parse_link(link) if url.isValid(): - url = unicode_type(url.toString(NO_URL_FORMATTING)) + url = str(url.toString(NO_URL_FORMATTING)) self.focus_self() with self.editing_cursor() as c: if is_image: @@ -692,7 +692,7 @@ def cf(): d.resize(d.sizeHint()) link, name, is_image = None, None, False if d.exec_() == QDialog.DialogCode.Accepted: - link, name = unicode_type(d.url.text()).strip(), unicode_type(d.name.text()).strip() + link, name = str(d.url.text()).strip(), str(d.name.text()).strip() is_image = d.treat_as_image.isChecked() return link, name, is_image diff --git a/src/calibre/gui2/complete2.py b/src/calibre/gui2/complete2.py index 6f90f3b479..fc9b02fb12 100644 --- a/src/calibre/gui2/complete2.py +++ b/src/calibre/gui2/complete2.py @@ -15,7 +15,6 @@ from calibre.utils.icu import sort_key, primary_startswith, primary_contains from calibre.gui2.widgets import EnComboBox, LineEditECM from calibre.utils.config import tweaks -from polyglot.builtins import unicode_type def containsq(x, prefix): @@ -108,7 +107,7 @@ def item_chosen(self, index): return self.hide() text = self.model().data(index, Qt.ItemDataRole.DisplayRole) - self.item_selected.emit(unicode_type(text)) + self.item_selected.emit(str(text)) def set_items(self, items): self.model().set_items(items) @@ -380,7 +379,7 @@ def text_edited(self, *args): def update_completions(self): ' Update the list of completions ' self.original_cursor_pos = cpos = self.cursorPosition() - text = unicode_type(self.text()) + text = str(self.text()) prefix = text[:cpos] complete_prefix = prefix.lstrip() if self.sep: @@ -397,7 +396,7 @@ def get_completed_text(self, text): cursor_pos = self.cursorPosition() self.original_cursor_pos = None # Split text - curtext = unicode_type(self.text()) + curtext = str(self.text()) before_text = curtext[:cursor_pos] after_text = curtext[cursor_pos:].rstrip() # Remove the completion prefix from the before text @@ -417,7 +416,7 @@ def get_completed_text(self, text): return before_text + completed_text, after_text def completion_selected(self, text): - before_text, after_text = self.get_completed_text(unicode_type(text)) + before_text, after_text = self.get_completed_text(str(text)) self.setText(before_text + after_text) self.setCursorPosition(len(before_text)) self.item_selected.emit(text) @@ -459,7 +458,7 @@ def set_add_separator(self, what): self.lineEdit().set_add_separator(what) def show_initial_value(self, what): - what = unicode_type(what) if what else u'' + what = str(what) if what else u'' self.setText(what) self.lineEdit().selectAll() @@ -487,7 +486,7 @@ def set_clear_button_enabled(self, val=True): # }}} def text(self): - return unicode_type(self.lineEdit().text()) + return str(self.lineEdit().text()) def selectAll(self): self.lineEdit().selectAll() diff --git a/src/calibre/gui2/convert/__init__.py b/src/calibre/gui2/convert/__init__.py index f5d35fe092..65c4c866d0 100644 --- a/src/calibre/gui2/convert/__init__.py +++ b/src/calibre/gui2/convert/__init__.py @@ -19,7 +19,6 @@ from calibre import prepare_string_for_xml from calibre.customize.ui import plugin_for_input_format from calibre.gui2.font_family_chooser import FontFamilyChooser -from polyglot.builtins import unicode_type def config_widget_for_input_plugin(plugin): @@ -101,7 +100,7 @@ def process_child(child): buddy = g.buddy() if buddy is not None and hasattr(buddy, '_help'): g._help = buddy._help - htext = unicode_type(buddy.toolTip()).strip() + htext = str(buddy.toolTip()).strip() g.setToolTip(htext) g.setWhatsThis(htext) g.__class__.enterEvent = lambda obj, event: self.set_help(getattr(obj, '_help', obj.toolTip())) @@ -152,18 +151,18 @@ def get_value(self, g): return g.value() elif isinstance(g, (QLineEdit, QTextEdit, QPlainTextEdit)): func = getattr(g, 'toPlainText', getattr(g, 'text', None))() - ans = unicode_type(func) + ans = str(func) if self.STRIP_TEXT_FIELDS: ans = ans.strip() if not ans: ans = None return ans elif isinstance(g, QFontComboBox): - return unicode_type(QFontInfo(g.currentFont()).family()) + return str(QFontInfo(g.currentFont()).family()) elif isinstance(g, FontFamilyChooser): return g.font_family elif isinstance(g, EncodingComboBox): - ans = unicode_type(g.currentText()).strip() + ans = str(g.currentText()).strip() try: codecs.lookup(ans) except: @@ -172,7 +171,7 @@ def get_value(self, g): ans = None return ans elif isinstance(g, QComboBox): - return unicode_type(g.currentText()) + return str(g.currentText()) elif isinstance(g, QCheckBox): return bool(g.isChecked()) elif isinstance(g, XPathEdit): @@ -251,7 +250,7 @@ def set_value(self, g, val): g.edit.setText(val if val else '') else: raise Exception('Can\'t set value %s in %s'%(repr(val), - unicode_type(g.objectName()))) + str(g.objectName()))) self.post_set_value(g, val) def set_help(self, msg): diff --git a/src/calibre/gui2/convert/bulk.py b/src/calibre/gui2/convert/bulk.py index 775f914c63..d4f7e1c143 100644 --- a/src/calibre/gui2/convert/bulk.py +++ b/src/calibre/gui2/convert/bulk.py @@ -21,7 +21,7 @@ from calibre.ebooks.conversion.config import sort_formats_by_preference, get_output_formats from calibre.utils.config import prefs from calibre.utils.logging import Log -from polyglot.builtins import unicode_type, native_string_type +from polyglot.builtins import native_string_type class BulkConfig(Config): @@ -128,7 +128,7 @@ def setup_output_formats(self, db, preferred_output_format): preferred_output_format and preferred_output_format \ in output_formats else sort_formats_by_preference(output_formats, [prefs['output_format']])[0] - self.output_formats.addItems((unicode_type(x.upper()) for x in output_formats)) + self.output_formats.addItems((str(x.upper()) for x in output_formats)) self.output_formats.setCurrentIndex(output_formats.index(preferred_output_format)) def accept(self): diff --git a/src/calibre/gui2/convert/debug.py b/src/calibre/gui2/convert/debug.py index 35be0ab653..ff068da456 100644 --- a/src/calibre/gui2/convert/debug.py +++ b/src/calibre/gui2/convert/debug.py @@ -12,7 +12,6 @@ from calibre.gui2.convert import Widget from calibre.gui2 import error_dialog, choose_dir from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import unicode_type class DebugWidget(Widget, Ui_Form): @@ -35,7 +34,7 @@ def set_debug_dir(self): def pre_commit_check(self): try: - x = unicode_type(self.opt_debug_pipeline.text()).strip() + x = str(self.opt_debug_pipeline.text()).strip() if not x: return True x = os.path.abspath(x) @@ -49,7 +48,7 @@ def pre_commit_check(self): import traceback det_msg = traceback.format_exc() error_dialog(self, _('Invalid debug folder'), - _('Failed to create debug folder')+': '+ unicode_type(self.opt_debug_pipeline.text()), + _('Failed to create debug folder')+': '+ str(self.opt_debug_pipeline.text()), det_msg=det_msg, show=True) return False return True diff --git a/src/calibre/gui2/convert/font_key.py b/src/calibre/gui2/convert/font_key.py index 168a44a709..6e615c5fb7 100644 --- a/src/calibre/gui2/convert/font_key.py +++ b/src/calibre/gui2/convert/font_key.py @@ -10,7 +10,6 @@ from calibre.gui2.convert.font_key_ui import Ui_Dialog from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import unicode_type class FontKeyChooser(QDialog, Ui_Dialog): @@ -67,7 +66,7 @@ def get_profile_values(self): @property def fsizes(self): - key = unicode_type(self.font_size_key.text()).strip() + key = str(self.font_size_key.text()).strip() return [float(x.strip()) for x in key.split(',' if ',' in key else ' ') if x.strip()] @property diff --git a/src/calibre/gui2/convert/heuristics.py b/src/calibre/gui2/convert/heuristics.py index c74310ebe9..d299d43592 100644 --- a/src/calibre/gui2/convert/heuristics.py +++ b/src/calibre/gui2/convert/heuristics.py @@ -12,7 +12,6 @@ from calibre.gui2.convert import Widget from calibre.utils.localization import localize_user_manual_link from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import unicode_type class HeuristicsWidget(Widget, Ui_Form): @@ -75,7 +74,7 @@ def set_value_handler(self, g, val): return True def load_histories(self): - val = unicode_type(self.opt_replace_scene_breaks.currentText()) + val = str(self.opt_replace_scene_breaks.currentText()) self.opt_replace_scene_breaks.clear() self.opt_replace_scene_breaks.lineEdit().setText('') @@ -92,7 +91,7 @@ def load_histories(self): def save_histories(self): rssb_history = [] - history_pats = [unicode_type(self.opt_replace_scene_breaks.lineEdit().text())] + [unicode_type(self.opt_replace_scene_breaks.itemText(i)) + history_pats = [str(self.opt_replace_scene_breaks.lineEdit().text())] + [str(self.opt_replace_scene_breaks.itemText(i)) for i in range(self.opt_replace_scene_breaks.count())] for p in history_pats[:10]: # Ensure we don't have duplicate items. diff --git a/src/calibre/gui2/convert/look_and_feel.py b/src/calibre/gui2/convert/look_and_feel.py index 0174dd4341..48b6f15259 100644 --- a/src/calibre/gui2/convert/look_and_feel.py +++ b/src/calibre/gui2/convert/look_and_feel.py @@ -13,7 +13,7 @@ from calibre.gui2.convert.look_and_feel_ui import Ui_Form from calibre.gui2.convert import Widget from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class LookAndFeelWidget(Widget, Ui_Form): @@ -55,7 +55,7 @@ def __init__(self, parent, get_option, get_help, db=None, book_id=None): def get_value_handler(self, g): if g is self.opt_change_justification: - ans = unicode_type(g.itemData(g.currentIndex()) or '') + ans = str(g.itemData(g.currentIndex()) or '') return ans if g is self.opt_filter_css: ans = set() @@ -64,10 +64,10 @@ def get_value_handler(self, g): if w.isChecked(): ans = ans.union(item) ans = ans.union({x.strip().lower() for x in - unicode_type(self.filter_css_others.text()).split(',')}) + str(self.filter_css_others.text()).split(',')}) return ','.join(ans) if ans else None if g is self.opt_font_size_mapping: - val = unicode_type(g.text()).strip() + val = str(g.text()).strip() val = [x.strip() for x in val.split(',' if ',' in val else ' ') if x.strip()] return ', '.join(val) or None if g is self.opt_transform_css_rules: @@ -77,7 +77,7 @@ def get_value_handler(self, g): def set_value_handler(self, g, val): if g is self.opt_change_justification: for i in range(g.count()): - c = unicode_type(g.itemData(i) or '') + c = str(g.itemData(i) or '') if val == c: g.setCurrentIndex(i) break @@ -114,7 +114,7 @@ def connect_gui_obj_handler(self, gui_obj, slot): def font_key_wizard(self): from calibre.gui2.convert.font_key import FontKeyChooser d = FontKeyChooser(self, self.opt_base_font_size.value(), - unicode_type(self.opt_font_size_mapping.text()).strip()) + str(self.opt_font_size_mapping.text()).strip()) if d.exec_() == QDialog.DialogCode.Accepted: self.opt_font_size_mapping.setText(', '.join(['%.1f'%x for x in d.fsizes])) diff --git a/src/calibre/gui2/convert/metadata.py b/src/calibre/gui2/convert/metadata.py index 1567e02f0d..f67447107f 100644 --- a/src/calibre/gui2/convert/metadata.py +++ b/src/calibre/gui2/convert/metadata.py @@ -21,7 +21,6 @@ from calibre.library.comments import comments_to_html from calibre.utils.config import tweaks from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import unicode_type def create_opf_file(db, book_id, opf_file=None): @@ -75,7 +74,7 @@ def change_cover(self, data): self.cover_data = data def deduce_author_sort(self, *args): - au = unicode_type(self.author.currentText()) + au = str(self.author.currentText()) au = re.sub(r'\s+et al\.$', '', au) authors = string_to_authors(au) self.author_sort.setText(self.db.author_sort_from_authors(authors)) @@ -159,30 +158,30 @@ def initialize_publisher(self): self.publisher.update_items_cache(self.db.new_api.all_field_names('publisher')) def get_title_and_authors(self): - title = unicode_type(self.title.text()).strip() + title = str(self.title.text()).strip() if not title: title = _('Unknown') - authors = unicode_type(self.author.text()).strip() + authors = str(self.author.text()).strip() authors = string_to_authors(authors) if authors else [_('Unknown')] return title, authors def get_metadata(self): title, authors = self.get_title_and_authors() mi = MetaInformation(title, authors) - publisher = unicode_type(self.publisher.text()).strip() + publisher = str(self.publisher.text()).strip() if publisher: mi.publisher = publisher - author_sort = unicode_type(self.author_sort.text()).strip() + author_sort = str(self.author_sort.text()).strip() if author_sort: mi.author_sort = author_sort comments = self.comment.html if comments: mi.comments = comments mi.series_index = float(self.series_index.value()) - series = unicode_type(self.series.currentText()).strip() + series = str(self.series.currentText()).strip() if series: mi.series = series - tags = [t.strip() for t in unicode_type(self.tags.text()).strip().split(',')] + tags = [t.strip() for t in str(self.tags.text()).strip().split(',')] if tags: mi.tags = tags @@ -190,7 +189,7 @@ def get_metadata(self): def select_cover(self): files = choose_images(self, 'change cover dialog', - _('Choose cover for ') + unicode_type(self.title.text())) + _('Choose cover for ') + str(self.title.text())) if not files: return _file = files[0] @@ -207,7 +206,7 @@ def select_cover(self): cover = f.read() except IOError as e: d = error_dialog(self.parent(), _('Error reading file'), - _("

There was an error reading from file:
") + _file + "


"+unicode_type(e)) + _("

There was an error reading from file:
") + _file + "


"+str(e)) d.exec_() if cover: pix = QPixmap() diff --git a/src/calibre/gui2/convert/page_setup.py b/src/calibre/gui2/convert/page_setup.py index f59b77cf7a..feabdcaa27 100644 --- a/src/calibre/gui2/convert/page_setup.py +++ b/src/calibre/gui2/convert/page_setup.py @@ -12,7 +12,6 @@ from calibre.gui2.convert import Widget from calibre.customize.ui import input_profiles, output_profiles from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import unicode_type class ProfileModel(QAbstractListModel): @@ -67,7 +66,7 @@ def __init__(self, parent, get_option, get_help, db=None, book_id=None): self.opt_output_profile.setToolTip('') def show_desc(self, index): - desc = unicode_type(index.model().data(index, Qt.ItemDataRole.StatusTipRole) or '') + desc = str(index.model().data(index, Qt.ItemDataRole.StatusTipRole) or '') self.profile_description.setText(desc) def connect_gui_obj_handler(self, g, slot): diff --git a/src/calibre/gui2/convert/regex_builder.py b/src/calibre/gui2/convert/regex_builder.py index a8590c4e88..34bae0dc4f 100644 --- a/src/calibre/gui2/convert/regex_builder.py +++ b/src/calibre/gui2/convert/regex_builder.py @@ -18,7 +18,7 @@ from calibre.ptempfile import TemporaryFile from calibre.utils.icu import utf16_length from calibre.utils.ipc.simple_worker import WorkerError, fork_job -from polyglot.builtins import native_string_type, unicode_type +from polyglot.builtins import native_string_type class RegexBuilder(QDialog, Ui_RegexBuilder): @@ -60,7 +60,7 @@ def save_state(self, result): gprefs['regex_builder_geometry'] = geom def regex_valid(self): - regex = unicode_type(self.regex.text()) + regex = str(self.regex.text()) if regex: try: compile_regular_expression(regex) @@ -88,8 +88,8 @@ class Pos: qt: int = 0 if self.regex_valid(): - text = unicode_type(self.preview.toPlainText()) - regex = unicode_type(self.regex.text()) + text = str(self.preview.toPlainText()) + regex = str(self.regex.text()) cursor = QTextCursor(self.preview.document()) extsel = QTextEdit.ExtraSelection() extsel.cursor = cursor @@ -110,7 +110,7 @@ class Pos: if self.match_locs: self.next.setEnabled(True) self.previous.setEnabled(True) - self.occurrences.setText(unicode_type(len(self.match_locs))) + self.occurrences.setText(str(len(self.match_locs))) def goto_previous(self): pos = self.preview.textCursor().position() @@ -209,12 +209,12 @@ def open_clicked(self): self.open_book(files[0]) def doc(self): - return unicode_type(self.preview.toPlainText()) + return str(self.preview.toPlainText()) class RegexEdit(QWidget, Ui_Edit): - doc_update = pyqtSignal(unicode_type) + doc_update = pyqtSignal(str) def __init__(self, parent=None): QWidget.__init__(self, parent) @@ -246,7 +246,7 @@ def doc(self): def setObjectName(self, *args): QWidget.setObjectName(self, *args) if hasattr(self, 'edit'): - self.edit.initialize('regex_edit_'+unicode_type(self.objectName())) + self.edit.initialize('regex_edit_'+str(self.objectName())) def set_msg(self, msg): self.msg.setText(msg) @@ -268,7 +268,7 @@ def break_cycles(self): @property def text(self): - return unicode_type(self.edit.text()) + return str(self.edit.text()) @property def regex(self): diff --git a/src/calibre/gui2/convert/search_and_replace.py b/src/calibre/gui2/convert/search_and_replace.py index d2c25ad736..2e028d2c58 100644 --- a/src/calibre/gui2/convert/search_and_replace.py +++ b/src/calibre/gui2/convert/search_and_replace.py @@ -17,7 +17,6 @@ from calibre.utils.localization import localize_user_manual_link from calibre.ebooks.conversion.search_replace import compile_regular_expression from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import unicode_type class SearchAndReplaceWidget(Widget, Ui_Form): @@ -193,7 +192,7 @@ def pre_commit_check(self): edit_search = self.sr_search.regex if edit_search: - edit_replace = unicode_type(self.sr_replace.text()) + edit_replace = str(self.sr_replace.text()) found = False for search, replace in definitions: if search == edit_search and replace == edit_replace: @@ -234,7 +233,7 @@ def get_definitions(self): for row in range(0, self.search_replace.rowCount()): colItems = [] for col in range(0, self.search_replace.columnCount()): - colItems.append(unicode_type(self.search_replace.item(row, col).text())) + colItems.append(str(self.search_replace.item(row, col).text())) ans.append(colItems) return ans diff --git a/src/calibre/gui2/convert/single.py b/src/calibre/gui2/convert/single.py index 641a90d688..5b9c1ef873 100644 --- a/src/calibre/gui2/convert/single.py +++ b/src/calibre/gui2/convert/single.py @@ -28,7 +28,7 @@ from calibre.gui2.convert.structure_detection import StructureDetectionWidget from calibre.gui2.convert.toc import TOCWidget from calibre.utils.config import prefs -from polyglot.builtins import native_string_type, unicode_type +from polyglot.builtins import native_string_type class GroupModel(QAbstractListModel): @@ -190,11 +190,11 @@ def restore_defaults(self): @property def input_format(self): - return unicode_type(self.input_formats.currentText()).lower() + return str(self.input_formats.currentText()).lower() @property def output_format(self): - return unicode_type(self.output_formats.currentText()).lower() + return str(self.output_formats.currentText()).lower() @property def manually_fine_tune_toc(self): @@ -213,7 +213,7 @@ def widget_factory(cls): self.plumber.get_option_help, self.db, self.book_id) self.mw = widget_factory(MetadataWidget) - self.setWindowTitle(_('Convert')+ ' ' + unicode_type(self.mw.title.text())) + self.setWindowTitle(_('Convert')+ ' ' + str(self.mw.title.text())) lf = widget_factory(LookAndFeelWidget) hw = widget_factory(HeuristicsWidget) sr = widget_factory(SearchAndReplaceWidget) @@ -265,8 +265,8 @@ def setup_input_output_formats(self, db, book_id, preferred_input_format, preferred_output_format in output_formats else \ sort_formats_by_preference(output_formats, [prefs['output_format']])[0] - self.input_formats.addItems((unicode_type(x.upper()) for x in input_formats)) - self.output_formats.addItems((unicode_type(x.upper()) for x in output_formats)) + self.input_formats.addItems((str(x.upper()) for x in input_formats)) + self.output_formats.addItems((str(x.upper()) for x in output_formats)) self.input_formats.setCurrentIndex(input_formats.index(input_format)) self.output_formats.setCurrentIndex(output_formats.index(preferred_output_format)) diff --git a/src/calibre/gui2/convert/txt_input.py b/src/calibre/gui2/convert/txt_input.py index 07d28c1612..106af84fd1 100644 --- a/src/calibre/gui2/convert/txt_input.py +++ b/src/calibre/gui2/convert/txt_input.py @@ -11,7 +11,7 @@ from calibre.gui2.convert import Widget from calibre.ebooks.conversion.plugins.txt_input import MD_EXTENSIONS from calibre.ebooks.conversion.config import OPTIONS -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues class PluginWidget(Widget, Ui_Form): @@ -50,7 +50,7 @@ def set_value_handler(self, g, val): def get_value_handler(self, g): if g is not self.opt_markdown_extensions: return Widget.get_value_handler(self, g) - return ', '.join(unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') for i in itervalues(self.md_map) if i.checkState()) + return ', '.join(str(i.data(Qt.ItemDataRole.UserRole) or '') for i in itervalues(self.md_map) if i.checkState()) def connect_gui_obj_handler(self, g, f): if g is not self.opt_markdown_extensions: diff --git a/src/calibre/gui2/convert/xpath_wizard.py b/src/calibre/gui2/convert/xpath_wizard.py index 9870e12625..81bd317e1c 100644 --- a/src/calibre/gui2/convert/xpath_wizard.py +++ b/src/calibre/gui2/convert/xpath_wizard.py @@ -11,7 +11,6 @@ from calibre.gui2.convert.xpath_wizard_ui import Ui_Form from calibre.gui2.convert.xexp_edit_ui import Ui_Form as Ui_Edit from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import unicode_type class WizardWidget(QWidget, Ui_Form): @@ -27,10 +26,10 @@ def __init__(self, parent=None): @property def xpath(self): - tag = unicode_type(self.tag.currentText()).strip() + tag = str(self.tag.currentText()).strip() if tag != '*': tag = 'h:'+tag - attr, val = map(unicode_type, (self.attribute.text(), self.value.text())) + attr, val = map(str, (self.attribute.text(), self.value.text())) attr, val = attr.strip(), val.strip() q = '' if attr: @@ -81,14 +80,14 @@ def wizard(self): def setObjectName(self, *args): QWidget.setObjectName(self, *args) if hasattr(self, 'edit'): - self.edit.initialize('xpath_edit_'+unicode_type(self.objectName())) + self.edit.initialize('xpath_edit_'+str(self.objectName())) def set_msg(self, msg): self.msg.setText(msg) @property def text(self): - return unicode_type(self.edit.text()) + return str(self.edit.text()) @property def xpath(self): diff --git a/src/calibre/gui2/css_transform_rules.py b/src/calibre/gui2/css_transform_rules.py index 195977a9e9..c928cabed9 100644 --- a/src/calibre/gui2/css_transform_rules.py +++ b/src/calibre/gui2/css_transform_rules.py @@ -17,7 +17,7 @@ from calibre.gui2.widgets2 import Dialog from calibre.utils.config import JSONConfig from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class RuleEdit(QWidget): # {{{ @@ -132,14 +132,14 @@ def rule(self): def rule(self, rule): def sc(name): c = getattr(self, name) - idx = c.findData(unicode_type(rule.get(name, ''))) + idx = c.findData(str(rule.get(name, ''))) if idx < 0: idx = 0 c.setCurrentIndex(idx) sc('action'), sc('match_type') - self.property.setText(unicode_type(rule.get('property', '')).strip()) - self.query.setText(unicode_type(rule.get('query', '')).strip()) - self.action_data.setText(unicode_type(rule.get('action_data', '')).strip()) + self.property.setText(str(rule.get('property', '')).strip()) + self.query.setText(str(rule.get('query', '')).strip()) + self.action_data.setText(str(rule.get('action_data', '')).strip()) self.update_state() def validate(self): diff --git a/src/calibre/gui2/custom_column_widgets.py b/src/calibre/gui2/custom_column_widgets.py index 81c10c54bf..bdf03984a4 100644 --- a/src/calibre/gui2/custom_column_widgets.py +++ b/src/calibre/gui2/custom_column_widgets.py @@ -24,7 +24,6 @@ from calibre.library.comments import comments_to_html from calibre.gui2.library.delegates import ClearingDoubleSpinBox, ClearingSpinBox from calibre.gui2.widgets2 import RatingEditor, DateTimeEdit as DateTimeEditBase -from polyglot.builtins import unicode_type class EditWithComplete(EWC): @@ -144,7 +143,7 @@ def setup_ui(self, parent): self.editor.setClearButtonEnabled(True) def setter(self, val): - self.editor.setText(unicode_type(val or '')) + self.editor.setText(str(val or '')) def getter(self): return self.editor.text().strip() @@ -167,7 +166,7 @@ def setup_ui(self, parent): self.widgets = [self._box] def setter(self, val): - self._tb.setPlainText(unicode_type(val or '')) + self._tb.setPlainText(str(val or '')) def getter(self): return self._tb.toPlainText() @@ -417,7 +416,7 @@ def setter(self, val): self._tb.wyswyg_dirtied() def getter(self): - val = unicode_type(self._tb.html).strip() + val = str(self._tb.html).strip() if not val: val = None return val @@ -545,12 +544,12 @@ def setter(self, val): def getter(self): if self.col_metadata['is_multiple']: - val = unicode_type(self.editor.text()).strip() + val = str(self.editor.text()).strip() ans = [x.strip() for x in val.split(self.sep['ui_to_list']) if x.strip()] if not ans: ans = None return ans - val = unicode_type(self.editor.currentText()).strip() + val = str(self.editor.currentText()).strip() if not val: val = None return val @@ -634,7 +633,7 @@ def initialize(self, book_id): self.initial_val, self.initial_index = self.current_val def getter(self): - n = unicode_type(self.name_widget.currentText()).strip() + n = str(self.name_widget.currentText()).strip() i = self.idx_widget.value() return n, i @@ -705,7 +704,7 @@ def setter(self, val): self.editor.setCurrentIndex(self.editor.findText(val)) def getter(self): - return unicode_type(self.editor.currentText()) + return str(self.editor.currentText()) def normalize_db_val(self, val): if val is None: @@ -860,7 +859,7 @@ def widget_factory(typ, key): wij.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred) l.setColumnMinimumWidth(0, label_width) wij.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) - t = unicode_type(wij.text()) + t = str(wij.text()) if t: if do_elision: wij.setText(elided_text(t, font=font_metrics, @@ -1269,7 +1268,7 @@ def initialize(self, book_id): self.a_c_checkbox.setChecked(False) def getter(self): - n = unicode_type(self.main_widget.currentText()).strip() + n = str(self.main_widget.currentText()).strip() autonumber = self.idx_widget.checkState() force = self.force_number.checkState() start = self.series_start_number.value() @@ -1343,7 +1342,7 @@ def set_to_undefined(self): self.main_widget.setCurrentIndex(0) def getter(self): - return unicode_type(self.main_widget.currentText()) + return str(self.main_widget.currentText()) def setter(self, val): if val is None: @@ -1471,10 +1470,10 @@ def getter(self): if self.col_metadata['is_multiple']: if not self.col_metadata['display'].get('is_names', False): return self.removing_widget.checkbox.isChecked(), \ - unicode_type(self.adding_widget.text()), \ - unicode_type(self.removing_widget.tags_box.text()) - return unicode_type(self.adding_widget.text()) - val = unicode_type(self.main_widget.currentText()).strip() + str(self.adding_widget.text()), \ + str(self.removing_widget.tags_box.text()) + return str(self.adding_widget.text()) + val = str(self.main_widget.currentText()).strip() if not val: val = None return val diff --git a/src/calibre/gui2/device.py b/src/calibre/gui2/device.py index 7a9664ea2e..6acd443e98 100644 --- a/src/calibre/gui2/device.py +++ b/src/calibre/gui2/device.py @@ -35,7 +35,7 @@ from calibre.utils.img import scale_image from calibre.library.save_to_disk import find_plugboard from calibre.ptempfile import PersistentTemporaryFile, force_unicode as filename_to_unicode -from polyglot.builtins import unicode_type, string_or_unicode +from polyglot.builtins import string_or_unicode from polyglot import queue # }}} @@ -107,7 +107,7 @@ def abort(self, err): call_job_done = True self._aborted = True self.failed = True - self._details = unicode_type(err) + self._details = str(err) self.exception = err if call_job_done: self.job_done() @@ -209,7 +209,7 @@ def do_connect(self, connected_devices, device_kind): tb = traceback.format_exc() if DEBUG or tb not in self.reported_errors: self.reported_errors.add(tb) - prints('Unable to open device', unicode_type(dev)) + prints('Unable to open device', str(dev)) prints(tb) continue self.after_device_connect(dev, device_kind) @@ -566,7 +566,7 @@ def _upload_books(self, files, names, on_card=None, metadata=None, plugboards=No self.connected_device.set_plugboards(plugboards, find_plugboard) if metadata and files and len(metadata) == len(files): for f, mi in zip(files, metadata): - if isinstance(f, unicode_type): + if isinstance(f, str): ext = f.rpartition('.')[-1].lower() cpb = find_plugboard( device_name_for_plugboards(self.connected_device), @@ -935,7 +935,7 @@ def show_open_feedback(self, devname, e): d.show() def auto_convert_question(self, msg, autos): - autos = '\n'.join(map(unicode_type, map(force_unicode, autos))) + autos = '\n'.join(map(str, map(force_unicode, autos))) return self.ask_a_yes_no_question( _('No suitable formats'), msg, ans_when_user_unavailable=True, @@ -1033,7 +1033,7 @@ def device_job_exception(self, job): try: if 'Could not read 32 bytes on the control bus.' in \ - unicode_type(job.details): + str(job.details): error_dialog(self, _('Error talking to device'), _('There was a temporary error talking to the ' 'device. Please unplug and reconnect the device ' @@ -1361,7 +1361,7 @@ def sync_catalogs(self, send_ids=None, do_auto_convert=True): names = [] for book_id, mi in zip(ids, metadata): prefix = ascii_filename(mi.title) - if not isinstance(prefix, unicode_type): + if not isinstance(prefix, str): prefix = prefix.decode(preferred_encoding, 'replace') prefix = ascii_filename(prefix) names.append('%s_%d%s'%(prefix, book_id, @@ -1439,7 +1439,7 @@ def sync_news(self, send_ids=None, do_auto_convert=True): names = [] for book_id, mi in zip(ids, metadata): prefix = ascii_filename(mi.title) - if not isinstance(prefix, unicode_type): + if not isinstance(prefix, str): prefix = prefix.decode(preferred_encoding, 'replace') prefix = ascii_filename(prefix) names.append('%s_%d%s'%(prefix, book_id, @@ -1518,7 +1518,7 @@ def sync_to_device(self, on_card, delete_from_library, if not a: a = _('Unknown') prefix = ascii_filename(t+' - '+a) - if not isinstance(prefix, unicode_type): + if not isinstance(prefix, str): prefix = prefix.decode(preferred_encoding, 'replace') prefix = ascii_filename(prefix) names.append('%s_%d%s'%(prefix, id, os.path.splitext(f)[1])) @@ -1639,7 +1639,7 @@ def books_uploaded(self, job): if job.exception is not None: if isinstance(job.exception, FreeSpaceError): - where = 'in main memory.' if 'memory' in unicode_type(job.exception) \ + where = 'in main memory.' if 'memory' in str(job.exception) \ else 'on the storage card.' titles = '\n'.join(['
  • '+mi.title+'
  • ' for mi in metadata]) @@ -1650,7 +1650,7 @@ def books_uploaded(self, job): d.exec_() elif isinstance(job.exception, WrongDestinationError): error_dialog(self, _('Incorrect destination'), - unicode_type(job.exception), show=True) + str(job.exception), show=True) else: self.device_job_exception(job) return diff --git a/src/calibre/gui2/device_drivers/configwidget.py b/src/calibre/gui2/device_drivers/configwidget.py index 36d4d28889..754d004ccc 100644 --- a/src/calibre/gui2/device_drivers/configwidget.py +++ b/src/calibre/gui2/device_drivers/configwidget.py @@ -14,7 +14,6 @@ from calibre.gui2.device_drivers.configwidget_ui import Ui_ConfigWidget from calibre.utils.formatter import validation_formatter from calibre.ebooks import BOOK_EXTENSIONS -from polyglot.builtins import unicode_type class ConfigWidget(QWidget, Ui_ConfigWidget): @@ -138,7 +137,7 @@ def down_column(self): def format_map(self): formats = [ - unicode_type(self.columns.item(i).data(Qt.ItemDataRole.UserRole) or '') + str(self.columns.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.columns.count()) if self.columns.item(i).checkState()==Qt.CheckState.Checked ] @@ -166,13 +165,13 @@ def validate(self): (', '.join(fmts)), self.device_name)): return False - tmpl = unicode_type(self.opt_save_template.text()) + tmpl = str(self.opt_save_template.text()) try: validation_formatter.validate(tmpl) return True except Exception as err: error_dialog(self, _('Invalid template'), '

    '+_('The template %s is invalid:')%tmpl + - '
    '+unicode_type(err), show=True) + '
    '+str(err), show=True) return False diff --git a/src/calibre/gui2/device_drivers/mtp_config.py b/src/calibre/gui2/device_drivers/mtp_config.py index 953d8fb021..2e067f9af4 100644 --- a/src/calibre/gui2/device_drivers/mtp_config.py +++ b/src/calibre/gui2/device_drivers/mtp_config.py @@ -19,7 +19,7 @@ from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.utils.date import parse_date from calibre.gui2.device_drivers.mtp_folder_browser import Browser, IgnoredFolders -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class FormatsConfig(QWidget): # {{{ @@ -50,7 +50,7 @@ def __init__(self, all_formats, format_map): @property def format_map(self): - return [unicode_type(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in + return [str(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked] def validate(self): @@ -97,7 +97,7 @@ def __init__(self, val): @property def template(self): - return unicode_type(self.t.text()).strip() + return str(self.t.text()).strip() def edit_template(self): t = TemplateDialog(self, self.template) @@ -114,7 +114,7 @@ def validate(self): except Exception as err: error_dialog(self, _('Invalid template'), '

    '+_('The template %s is invalid:')%tmpl + - '
    '+unicode_type(err), show=True) + '
    '+str(err), show=True) return False # }}} @@ -155,7 +155,7 @@ def browse(self): @property def value(self): - ans = [x.strip() for x in unicode_type(self.t.text()).strip().split(',')] + ans = [x.strip() for x in str(self.t.text()).strip().split(',')] return [x for x in ans if x] # }}} @@ -187,13 +187,13 @@ def __init__(self, devs, blacklist): @property def blacklist(self): - return [unicode_type(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in + return [str(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked] def ignore_device(self, snum): for i in range(self.f.count()): i = self.f.item(i) - c = unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') + c = str(i.data(Qt.ItemDataRole.UserRole) or '') if c == snum: i.setCheckState(Qt.CheckState.Checked) break @@ -264,10 +264,10 @@ def removed(self): @property def rule(self): - folder = unicode_type(self.folder.text()).strip() + folder = str(self.folder.text()).strip() if folder: return ( - unicode_type(self.fmt.itemData(self.fmt.currentIndex()) or ''), + str(self.fmt.itemData(self.fmt.currentIndex()) or ''), folder ) return None diff --git a/src/calibre/gui2/device_drivers/mtp_folder_browser.py b/src/calibre/gui2/device_drivers/mtp_folder_browser.py index f712bc079c..753bb470f1 100644 --- a/src/calibre/gui2/device_drivers/mtp_folder_browser.py +++ b/src/calibre/gui2/device_drivers/mtp_folder_browser.py @@ -12,7 +12,6 @@ QDialogButtonBox, QVBoxLayout, QSize, pyqtSignal, QIcon, QLabel) from calibre.gui2 import file_icon_provider -from polyglot.builtins import unicode_type def browser_item(f, parent): @@ -200,11 +199,11 @@ def ignored_folders(self): for node in self.iterchildren(w.invisibleRootItem()): if node.checkState(0) == Qt.CheckState.Checked: continue - path = unicode_type(node.data(0, Qt.ItemDataRole.UserRole) or '') + path = str(node.data(0, Qt.ItemDataRole.UserRole) or '') parent = path.rpartition('/')[0] if '/' not in path or icu_lower(parent) not in folders: folders.add(icu_lower(path)) - ans[unicode_type(w.storage.storage_id)] = list(folders) + ans[str(w.storage.storage_id)] = list(folders) return ans diff --git a/src/calibre/gui2/device_drivers/tabbed_device_config.py b/src/calibre/gui2/device_drivers/tabbed_device_config.py index 2ccdb64ff5..6dddd9987f 100644 --- a/src/calibre/gui2/device_drivers/tabbed_device_config.py +++ b/src/calibre/gui2/device_drivers/tabbed_device_config.py @@ -15,7 +15,6 @@ from calibre.ebooks import BOOK_EXTENSIONS from calibre.gui2.device_drivers.mtp_config import (FormatsConfig, TemplateConfig) from calibre.devices.usbms.driver import debug_print -from polyglot.builtins import unicode_type def wrap_msg(msg): @@ -339,11 +338,11 @@ def extra_customization(self): if hasattr(self.opt_extra_customization[i], 'isChecked'): ec.append(self.opt_extra_customization[i].isChecked()) elif hasattr(self.opt_extra_customization[i], 'currentText'): - ec.append(unicode_type(self.opt_extra_customization[i].currentText()).strip()) + ec.append(str(self.opt_extra_customization[i].currentText()).strip()) else: - ec.append(unicode_type(self.opt_extra_customization[i].text()).strip()) + ec.append(str(self.opt_extra_customization[i].text()).strip()) else: - ec = unicode_type(self.opt_extra_customization.text()).strip() + ec = str(self.opt_extra_customization.text()).strip() if not ec: ec = None diff --git a/src/calibre/gui2/dialogs/add_empty_book.py b/src/calibre/gui2/dialogs/add_empty_book.py index 6323ee1f83..2b60a73cc0 100644 --- a/src/calibre/gui2/dialogs/add_empty_book.py +++ b/src/calibre/gui2/dialogs/add_empty_book.py @@ -13,7 +13,6 @@ from calibre.gui2.complete2 import EditWithComplete from calibre.utils.config import tweaks from calibre.gui2 import gprefs -from polyglot.builtins import unicode_type class AddEmptyBookDialog(QDialog): @@ -164,11 +163,11 @@ def qty_to_add(self): @property def selected_authors(self): - return string_to_authors(unicode_type(self.authors_combo.text())) + return string_to_authors(str(self.authors_combo.text())) @property def selected_series(self): - return unicode_type(self.series_combo.text()) + return str(self.series_combo.text()) @property def selected_title(self): diff --git a/src/calibre/gui2/dialogs/add_from_isbn.py b/src/calibre/gui2/dialogs/add_from_isbn.py index 8942178e53..8eb6f716ea 100644 --- a/src/calibre/gui2/dialogs/add_from_isbn.py +++ b/src/calibre/gui2/dialogs/add_from_isbn.py @@ -15,7 +15,6 @@ from calibre.constants import iswindows from calibre.ebooks.metadata import check_isbn from calibre.gui2 import error_dialog, gprefs, question_dialog -from polyglot.builtins import unicode_type class AddFromISBN(QDialog): @@ -26,7 +25,7 @@ def __init__(self, parent=None): path = 'C:\\Users\\kovid\\e-books\\some_book.epub' if iswindows else \ '/Users/kovid/e-books/some_book.epub' - self.label.setText(unicode_type(self.label.text())%path) + self.label.setText(str(self.label.text())%path) self.isbns = [] self.books = [] @@ -75,9 +74,9 @@ def setup_ui(self): def paste(self, *args): app = QApplication.instance() c = app.clipboard() - txt = unicode_type(c.text()).strip() + txt = str(c.text()).strip() if txt: - old = unicode_type(self.isbn_box.toPlainText()).strip() + old = str(self.isbn_box.toPlainText()).strip() new = old + '\n' + txt self.isbn_box.setPlainText(new) @@ -86,13 +85,13 @@ def check_for_existing(self): return self._check_for_existing.isChecked() def accept(self, *args): - tags = unicode_type(self.add_tags.text()).strip().split(',') + tags = str(self.add_tags.text()).strip().split(',') tags = list(filter(None, [x.strip() for x in tags])) gprefs['add from ISBN tags'] = tags gprefs['add from ISBN dup check'] = self.check_for_existing self.set_tags = tags bad = set() - for line in unicode_type(self.isbn_box.toPlainText()).strip().splitlines(): + for line in str(self.isbn_box.toPlainText()).strip().splitlines(): line = line.strip() if not line: continue diff --git a/src/calibre/gui2/dialogs/authors_edit.py b/src/calibre/gui2/dialogs/authors_edit.py index 3394341530..bb6bf89ef0 100644 --- a/src/calibre/gui2/dialogs/authors_edit.py +++ b/src/calibre/gui2/dialogs/authors_edit.py @@ -15,7 +15,6 @@ from calibre.gui2 import gprefs from calibre.gui2.complete2 import EditWithComplete from calibre.ebooks.metadata import string_to_authors -from polyglot.builtins import unicode_type class ItemDelegate(QStyledItemDelegate): @@ -30,12 +29,12 @@ def sizeHint(self, *args): return QStyledItemDelegate.sizeHint(self, *args) + QSize(0, 15) def setEditorData(self, editor, index): - name = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') + name = str(index.data(Qt.ItemDataRole.DisplayRole) or '') editor.setText(name) editor.lineEdit().selectAll() def setModelData(self, editor, model, index): - authors = string_to_authors(unicode_type(editor.text())) + authors = string_to_authors(str(editor.text())) model.setData(index, authors[0]) self.edited.emit(index.row()) @@ -89,10 +88,10 @@ def mark_as_editable(self): def edited(self, i): item = self.item(i) - q = unicode_type(item.text()) + q = str(item.text()) remove = [] for j in range(self.count()): - if i != j and unicode_type(self.item(j).text()) == q: + if i != j and str(self.item(j).text()) == q: remove.append(j) for x in sorted(remove, reverse=True): self.takeItem(x) @@ -177,7 +176,7 @@ def reject(self): def authors(self): ans = [] for i in range(self.al.count()): - ans.append(unicode_type(self.al.item(i).text())) + ans.append(str(self.al.item(i).text())) return ans or [_('Unknown')] def add_author(self): diff --git a/src/calibre/gui2/dialogs/book_info.py b/src/calibre/gui2/dialogs/book_info.py index a6674498a9..2d078cc5c3 100644 --- a/src/calibre/gui2/dialogs/book_info.py +++ b/src/calibre/gui2/dialogs/book_info.py @@ -19,7 +19,6 @@ from calibre.gui2.ui import get_gui from calibre.gui2.widgets import CoverView from calibre.gui2.widgets2 import Dialog, HTMLDisplay -from polyglot.builtins import unicode_type class Cover(CoverView): @@ -195,9 +194,9 @@ def __init__(self, parent, view, row, link_delegate): self.ps = QShortcut(QKeySequence('Alt+Left'), self) self.ps.activated.connect(self.previous) self.next_button.setToolTip(_('Next [%s]')% - unicode_type(self.ns.key().toString(QKeySequence.SequenceFormat.NativeText))) + str(self.ns.key().toString(QKeySequence.SequenceFormat.NativeText))) self.previous_button.setToolTip(_('Previous [%s]')% - unicode_type(self.ps.key().toString(QKeySequence.SequenceFormat.NativeText))) + str(self.ps.key().toString(QKeySequence.SequenceFormat.NativeText))) geom = QCoreApplication.instance().desktop().availableGeometry(self) screen_height = geom.height() - 100 @@ -231,7 +230,7 @@ def configure(self): self.refresh(self.current_row, mi=mi) def on_link_clicked(self, qurl): - link = unicode_type(qurl.toString(NO_URL_FORMATTING)) + link = str(qurl.toString(NO_URL_FORMATTING)) self.link_delegate(link) def done(self, r): diff --git a/src/calibre/gui2/dialogs/catalog.py b/src/calibre/gui2/dialogs/catalog.py index 84166111e2..62ddc6953d 100644 --- a/src/calibre/gui2/dialogs/catalog.py +++ b/src/calibre/gui2/dialogs/catalog.py @@ -18,7 +18,6 @@ from calibre.customize.ui import catalog_plugins, config from calibre.gui2 import dynamic, info_dialog from calibre.gui2.dialogs.catalog_ui import Ui_Dialog -from polyglot.builtins import unicode_type class Catalog(QDialog, Ui_Dialog): @@ -36,7 +35,7 @@ def __init__(self, parent, dbspec, ids, db): self.dbspec, self.ids = dbspec, ids # Display the number of books we've been passed - self.count.setText(unicode_type(self.count.text()).format(len(ids))) + self.count.setText(str(self.count.text()).format(len(ids))) # Display the last-used title self.title.setText(dynamic.get('catalog_last_used_title', @@ -158,7 +157,7 @@ def options_widget(self): return ans def show_plugin_tab(self, idx): - cf = unicode_type(self.format.currentText()).lower() + cf = str(self.format.currentText()).lower() while self.tabs.count() > 1: self.tabs.removeTab(1) for pw in self.widgets: @@ -176,7 +175,7 @@ def show_plugin_tab(self, idx): self.buttonBox.button(QDialogButtonBox.StandardButton.Help).setVisible(False) def format_changed(self, idx): - cf = unicode_type(self.format.currentText()) + cf = str(self.format.currentText()) if cf in self.sync_enabled_formats: self.sync.setEnabled(True) else: @@ -187,7 +186,7 @@ def settings_changed(self): ''' When title/format change, invalidate Preset in E-book options tab ''' - cf = unicode_type(self.format.currentText()).lower() + cf = str(self.format.currentText()).lower() if cf in ('azw3', 'epub', 'mobi') and hasattr(self.options_widget, 'settings_changed'): self.options_widget.settings_changed("title/format") @@ -200,9 +199,9 @@ def fmt_options(self): return ans def save_catalog_settings(self): - self.catalog_format = unicode_type(self.format.currentText()) + self.catalog_format = str(self.format.currentText()) dynamic.set('catalog_preferred_format', self.catalog_format) - self.catalog_title = unicode_type(self.title.text()) + self.catalog_title = str(self.title.text()) dynamic.set('catalog_last_used_title', self.catalog_title) self.catalog_sync = bool(self.sync.isChecked()) dynamic.set('catalog_sync_to_device', self.catalog_sync) diff --git a/src/calibre/gui2/dialogs/check_library.py b/src/calibre/gui2/dialogs/check_library.py index 589913666c..e843e31a08 100644 --- a/src/calibre/gui2/dialogs/check_library.py +++ b/src/calibre/gui2/dialogs/check_library.py @@ -17,7 +17,6 @@ from calibre.library.check_library import CheckLibrary, CHECKS from calibre.utils.recycle_bin import delete_file, delete_tree from calibre import prints, as_unicode -from polyglot.builtins import unicode_type class DBCheck(QDialog): # {{{ @@ -238,8 +237,8 @@ def do_exec(self): return True def accept(self): - self.db.new_api.set_pref('check_library_ignore_extensions', unicode_type(self.ext_ignores.text())) - self.db.new_api.set_pref('check_library_ignore_names', unicode_type(self.name_ignores.text())) + self.db.new_api.set_pref('check_library_ignore_extensions', str(self.ext_ignores.text())) + self.db.new_api.set_pref('check_library_ignore_names', str(self.name_ignores.text())) QDialog.accept(self) def box_to_list(self, txt): @@ -247,8 +246,8 @@ def box_to_list(self, txt): def run_the_check(self): checker = CheckLibrary(self.db.library_path, self.db) - checker.scan_library(self.box_to_list(unicode_type(self.name_ignores.text())), - self.box_to_list(unicode_type(self.ext_ignores.text()))) + checker.scan_library(self.box_to_list(str(self.name_ignores.text())), + self.box_to_list(str(self.ext_ignores.text()))) plaintext = [] @@ -409,7 +408,7 @@ def delete_marked(self): for it in items: if it.checkState(2) == Qt.CheckState.Checked: try: - p = os.path.join(self.db.library_path, unicode_type(it.text(2))) + p = os.path.join(self.db.library_path, str(it.text(2))) if os.path.isdir(p): delete_tree(p) else: @@ -417,7 +416,7 @@ def delete_marked(self): except: prints('failed to delete', os.path.join(self.db.library_path, - unicode_type(it.text(2)))) + str(it.text(2)))) self.run_the_check() def fix_missing_formats(self): diff --git a/src/calibre/gui2/dialogs/choose_format_device.py b/src/calibre/gui2/dialogs/choose_format_device.py index a0b586b465..bfe0f2da23 100644 --- a/src/calibre/gui2/dialogs/choose_format_device.py +++ b/src/calibre/gui2/dialogs/choose_format_device.py @@ -7,7 +7,6 @@ from calibre.gui2 import file_icon_provider from calibre.gui2.dialogs.choose_format_device_ui import Ui_ChooseFormatDeviceDialog -from polyglot.builtins import unicode_type class ChooseFormatDeviceDialog(QDialog, Ui_ChooseFormatDeviceDialog): @@ -51,5 +50,5 @@ def format(self): return self._format def accept(self): - self._format = unicode_type(self.formats.currentItem().text(0)) + self._format = str(self.formats.currentItem().text(0)) return QDialog.accept(self) diff --git a/src/calibre/gui2/dialogs/choose_library.py b/src/calibre/gui2/dialogs/choose_library.py index 1976496eb7..902826bc1a 100644 --- a/src/calibre/gui2/dialogs/choose_library.py +++ b/src/calibre/gui2/dialogs/choose_library.py @@ -17,7 +17,6 @@ from calibre.constants import (filesystem_encoding, iswindows, get_portable_base) from calibre import isbytestring, patheq, force_unicode -from polyglot.builtins import unicode_type class ProgressDialog(PD): @@ -55,7 +54,7 @@ def __init__(self, db, callback, parent): lp = db.library_path if isbytestring(lp): lp = lp.decode(filesystem_encoding) - loc = unicode_type(self.old_location.text()).format(lp) + loc = str(self.old_location.text()).format(lp) self.old_location.setText(loc) self.browse_button.clicked.connect(self.choose_loc) self.empty_library.toggled.connect(self.empty_library_toggled) @@ -169,7 +168,7 @@ def accept(self): action = 'existing' elif self.empty_library.isChecked(): action = 'new' - text = unicode_type(self.location.text()).strip() + text = str(self.location.text()).strip() if not text: return error_dialog(self, _('No location'), _('No location selected'), show=True) diff --git a/src/calibre/gui2/dialogs/custom_recipes.py b/src/calibre/gui2/dialogs/custom_recipes.py index 4ff7fd1c1c..0242d5c4d0 100644 --- a/src/calibre/gui2/dialogs/custom_recipes.py +++ b/src/calibre/gui2/dialogs/custom_recipes.py @@ -20,7 +20,7 @@ from calibre.gui2.tweak_book.editor.text import TextEdit from calibre.web.feeds.recipes.collection import get_builtin_recipe_by_id from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import iteritems, unicode_type, as_unicode +from polyglot.builtins import iteritems, as_unicode from calibre.gui2.search_box import SearchBox2 from polyglot.builtins import as_bytes @@ -125,14 +125,14 @@ def py3_repr(x): ans = repr(x) if isinstance(x, bytes) and not ans.startswith('b'): ans = 'b' + ans - if isinstance(x, unicode_type) and ans.startswith('u'): + if isinstance(x, str) and ans.startswith('u'): ans = ans[1:] return ans def options_to_recipe_source(title, oldest_article, max_articles_per_feed, feeds): classname = 'BasicUserRecipe%d' % int(time.time()) - title = unicode_type(title).strip() or classname + title = str(title).strip() or classname indent = ' ' * 8 if feeds: if len(feeds[0]) == 1: diff --git a/src/calibre/gui2/dialogs/delete_matching_from_device.py b/src/calibre/gui2/dialogs/delete_matching_from_device.py index 672bf6ce75..2a0cc07bd1 100644 --- a/src/calibre/gui2/dialogs/delete_matching_from_device.py +++ b/src/calibre/gui2/dialogs/delete_matching_from_device.py @@ -13,7 +13,6 @@ from calibre.gui2.dialogs.delete_matching_from_device_ui import \ Ui_DeleteMatchingFromDeviceDialog from calibre.utils.date import UNDEFINED_DATE -from polyglot.builtins import unicode_type class tableItem(QTableWidgetItem): @@ -119,6 +118,6 @@ def accepted(self): if self.table.item(row, 0).checkState() == Qt.CheckState.Unchecked: continue (model, id, path) = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole) - path = unicode_type(path) + path = str(path) self.result.append((model, id, path)) return diff --git a/src/calibre/gui2/dialogs/device_category_editor.py b/src/calibre/gui2/dialogs/device_category_editor.py index 1a816c6e95..fe1193c0e5 100644 --- a/src/calibre/gui2/dialogs/device_category_editor.py +++ b/src/calibre/gui2/dialogs/device_category_editor.py @@ -7,7 +7,6 @@ from calibre.gui2.dialogs.device_category_editor_ui import Ui_DeviceCategoryEditor from calibre.gui2 import question_dialog, error_dialog -from polyglot.builtins import unicode_type class ListWidgetItem(QListWidgetItem): @@ -93,7 +92,7 @@ def finish_editing(self, item): return if item.text() != item.initial_text(): id_ = int(item.data(Qt.ItemDataRole.UserRole)) - self.to_rename[id_] = unicode_type(item.text()) + self.to_rename[id_] = str(item.text()) def rename_tag(self): item = self.available_tags.currentItem() @@ -112,7 +111,7 @@ def delete_tags(self): error_dialog(self, _('No items selected'), _('You must select at least one item from the list.')).exec_() return - ct = ', '.join([unicode_type(item.text()) for item in deletes]) + ct = ', '.join([str(item.text()) for item in deletes]) if not question_dialog(self, _('Are you sure?'), '

    '+_('Are you sure you want to delete the following items?')+'
    '+ct): return diff --git a/src/calibre/gui2/dialogs/duplicates.py b/src/calibre/gui2/dialogs/duplicates.py index 45f48319f0..961926cdb8 100644 --- a/src/calibre/gui2/dialogs/duplicates.py +++ b/src/calibre/gui2/dialogs/duplicates.py @@ -15,7 +15,6 @@ from calibre.gui2 import gprefs from calibre.ebooks.metadata import authors_to_string from calibre.utils.icu import primary_sort_key -from polyglot.builtins import unicode_type class DuplicatesQuestion(QDialog): @@ -126,7 +125,7 @@ def add_child(text): index_is_id=True) or '').split(',')]) def key(x): - return primary_sort_key(unicode_type(author_text[x])) + return primary_sort_key(str(author_text[x])) for book_id in sorted(matching_books, key=key): add_child(ta%dict( @@ -151,10 +150,10 @@ def as_text(self): for i in range(self.dup_list.topLevelItemCount()): x = self.dup_list.topLevelItem(i) check = '✓' if x.checkState(0) == Qt.CheckState.Checked else '✗' - title = '%s %s' % (check, unicode_type(x.text(0))) + title = '%s %s' % (check, str(x.text(0))) dups = [] for child in (x.child(j) for j in range(x.childCount())): - dups.append('\t' + unicode_type(child.text(0))) + dups.append('\t' + str(child.text(0))) entries.append(title + '\n' + '\n'.join(dups)) return '\n\n'.join(entries) diff --git a/src/calibre/gui2/dialogs/edit_authors_dialog.py b/src/calibre/gui2/dialogs/edit_authors_dialog.py index 100bbeb2dd..acd1d3de0f 100644 --- a/src/calibre/gui2/dialogs/edit_authors_dialog.py +++ b/src/calibre/gui2/dialogs/edit_authors_dialog.py @@ -17,7 +17,6 @@ from calibre.utils.config import prefs from calibre.utils.config_base import tweaks from calibre.utils.icu import sort_key, primary_contains, contains, primary_startswith -from polyglot.builtins import unicode_type QT_HIDDEN_CLEAR_ACTION = '_q_qlineeditclearaction' @@ -26,14 +25,14 @@ class tableItem(QTableWidgetItem): def __init__(self, txt): QTableWidgetItem.__init__(self, txt) - self.sort_key = sort_key(unicode_type(txt)) + self.sort_key = sort_key(str(txt)) def setText(self, txt): - self.sort_key = sort_key(unicode_type(txt)) + self.sort_key = sort_key(str(txt)) QTableWidgetItem.setText(self, txt) def set_sort_key(self): - self.sort_key = sort_key(unicode_type(self.text())) + self.sort_key = sort_key(str(self.text())) def __ge__(self, other): return self.sort_key >= other.sort_key @@ -184,7 +183,7 @@ def do_filter(self): def show_table(self, id_to_select, select_sort, select_link, is_first_letter): auts_to_show = {t[0] for t in self.find_aut_func(use_virtual_library=self.apply_vl_checkbox.isChecked())} - filter_text = icu_lower(unicode_type(self.filter_box.text())) + filter_text = icu_lower(str(self.filter_box.text())) if filter_text: auts_to_show = {id_ for id_ in auts_to_show if self.string_contains(filter_text, icu_lower(self.authors[id_]['name']))} @@ -234,7 +233,7 @@ def show_table(self, id_to_select, select_sort, select_link, is_first_letter): use_as = tweaks['categories_use_field_for_author_name'] == 'author_sort' for row in range(0, len(auts_to_show)): if is_first_letter: - item_txt = unicode_type(self.table.item(row, 1).text() if use_as + item_txt = str(self.table.item(row, 1).text() if use_as else self.table.item(row, 0).text()) if primary_startswith(item_txt, id_to_select): select_item = self.table.item(row, 1 if use_as else 0) @@ -340,32 +339,32 @@ def search_in_book_list(self): from calibre.gui2.ui import get_gui row = self.context_item.row() get_gui().search.set_search_string('authors:="%s"' % - unicode_type(self.table.item(row, 0).text()).replace(r'"', r'\"')) + str(self.table.item(row, 0).text()).replace(r'"', r'\"')) def copy_to_clipboard(self): cb = QApplication.clipboard() - cb.setText(unicode_type(self.context_item.text())) + cb.setText(str(self.context_item.text())) def paste_from_clipboard(self): cb = QApplication.clipboard() self.context_item.setText(cb.text()) def upper_case(self): - self.context_item.setText(icu_upper(unicode_type(self.context_item.text()))) + self.context_item.setText(icu_upper(str(self.context_item.text()))) def lower_case(self): - self.context_item.setText(icu_lower(unicode_type(self.context_item.text()))) + self.context_item.setText(icu_lower(str(self.context_item.text()))) def swap_case(self): - self.context_item.setText(unicode_type(self.context_item.text()).swapcase()) + self.context_item.setText(str(self.context_item.text()).swapcase()) def title_case(self): from calibre.utils.titlecase import titlecase - self.context_item.setText(titlecase(unicode_type(self.context_item.text()))) + self.context_item.setText(titlecase(str(self.context_item.text()))) def capitalize(self): from calibre.utils.icu import capitalize - self.context_item.setText(capitalize(unicode_type(self.context_item.text()))) + self.context_item.setText(capitalize(str(self.context_item.text()))) def copy_aus_to_au(self): row = self.context_item.row() @@ -397,7 +396,7 @@ def do_find(self): self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(False) self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setAutoDefault(False) - st = icu_lower(unicode_type(self.find_box.currentText())) + st = icu_lower(str(self.find_box.currentText())) if not st: return for _ in range(0, self.table.rowCount()*2): @@ -405,7 +404,7 @@ def do_find(self): r = (self.start_find_pos//2) % self.table.rowCount() c = self.start_find_pos % 2 item = self.table.item(r, c) - text = icu_lower(unicode_type(item.text())) + text = icu_lower(str(item.text())) if st in text: self.table.setCurrentItem(item) self.table.setFocus(True) @@ -445,10 +444,10 @@ def do_recalc_author_sort(self): for row in range(0,self.table.rowCount()): item_aut = self.table.item(row, 0) id_ = int(item_aut.data(Qt.ItemDataRole.UserRole)) - aut = unicode_type(item_aut.text()).strip() + aut = str(item_aut.text()).strip() item_aus = self.table.item(row, 1) # Sometimes trailing commas are left by changing between copy algs - aus = unicode_type(author_to_author_sort(aut)).rstrip(',') + aus = str(author_to_author_sort(aut)).rstrip(',') item_aus.setText(aus) self.authors[id_]['sort'] = aus self.set_icon(item_aus, id_) @@ -458,7 +457,7 @@ def do_recalc_author_sort(self): def do_auth_sort_to_author(self): self.table.cellChanged.disconnect() for row in range(0,self.table.rowCount()): - aus = unicode_type(self.table.item(row, 1).text()).strip() + aus = str(self.table.item(row, 1).text()).strip() item_aut = self.table.item(row, 0) id_ = int(item_aut.data(Qt.ItemDataRole.UserRole)) item_aut.setText(aus) @@ -469,7 +468,7 @@ def do_auth_sort_to_author(self): def set_icon(self, item, id_): col_name = self.get_column_name(item.column()) - if unicode_type(item.text()) != self.original_authors[id_][col_name]: + if str(item.text()) != self.original_authors[id_][col_name]: item.setIcon(self.edited_icon) else: item.setIcon(self.empty_icon) @@ -478,7 +477,7 @@ def cell_changed(self, row, col): id_ = int(self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)) if col == 0: item = self.table.item(row, 0) - aut = unicode_type(item.text()).strip() + aut = str(item.text()).strip() aut_list = string_to_authors(aut) if len(aut_list) != 1: error_dialog(self.parent(), _('Invalid author name'), @@ -497,6 +496,6 @@ def cell_changed(self, row, col): item = self.table.item(row, col) item.set_sort_key() self.set_icon(item, id_) - self.authors[id_][self.get_column_name(col)] = unicode_type(item.text()) + self.authors[id_][self.get_column_name(col)] = str(item.text()) self.table.setCurrentItem(item) self.table.scrollToItem(item) diff --git a/src/calibre/gui2/dialogs/enum_values_edit.py b/src/calibre/gui2/dialogs/enum_values_edit.py index 682ffebb31..700e169edd 100644 --- a/src/calibre/gui2/dialogs/enum_values_edit.py +++ b/src/calibre/gui2/dialogs/enum_values_edit.py @@ -8,7 +8,6 @@ QAbstractItemView, QComboBox) from calibre.gui2 import error_dialog, gprefs -from polyglot.builtins import unicode_type class EnumValuesEdit(QDialog): @@ -44,7 +43,7 @@ def __init__(self, parent, db, key): self.del_button.clicked.connect(self.del_line) - self.all_colors = {unicode_type(s) for s in list(QColor.colorNames())} + self.all_colors = {str(s) for s in list(QColor.colorNames())} tl = QVBoxLayout() l.addItem(tl, 0, 1) @@ -153,13 +152,13 @@ def accept(self): values = [] colors = [] for i in range(0, self.table.rowCount()): - v = unicode_type(self.table.item(i, 0).text()) + v = str(self.table.item(i, 0).text()) if not v: error_dialog(self, _('Empty value'), _('Empty values are not allowed'), show=True) return values.append(v) - c = unicode_type(self.table.cellWidget(i, 1).currentText()) + c = str(self.table.cellWidget(i, 1).currentText()) if c: colors.append(c) diff --git a/src/calibre/gui2/dialogs/match_books.py b/src/calibre/gui2/dialogs/match_books.py index a6c8b42c08..713bb70e5a 100644 --- a/src/calibre/gui2/dialogs/match_books.py +++ b/src/calibre/gui2/dialogs/match_books.py @@ -13,7 +13,6 @@ from calibre.gui2 import gprefs, error_dialog from calibre.gui2.dialogs.match_books_ui import Ui_MatchBooks from calibre.utils.icu import sort_key -from polyglot.builtins import unicode_type class TableItem(QTableWidgetItem): @@ -126,7 +125,7 @@ def keyPressEvent(self, e): QDialog.keyPressEvent(self, e) def do_search(self): - query = unicode_type(self.search_text.text()) + query = str(self.search_text.text()) if not query: d = error_dialog(self.gui, _('Match books'), _('You must enter a search expression into the search field')) diff --git a/src/calibre/gui2/dialogs/message_box.py b/src/calibre/gui2/dialogs/message_box.py index 64a6e164c2..5b3f9ce89f 100644 --- a/src/calibre/gui2/dialogs/message_box.py +++ b/src/calibre/gui2/dialogs/message_box.py @@ -15,7 +15,6 @@ from calibre.constants import __version__, isfrozen from calibre.gui2 import gprefs -from polyglot.builtins import unicode_type class Icon(QWidget): @@ -434,13 +433,13 @@ def copy_to_clipboard(self, *args): QApplication.clipboard().setText( 'calibre, version %s (%s, embedded-python: %s)\n%s: %s\n\n%s' % (__version__, sys.platform, isfrozen, - unicode_type(self.windowTitle()), unicode_type(d.toPlainText()), - unicode_type(self.det_msg.toPlainText()))) + str(self.windowTitle()), str(d.toPlainText()), + str(self.det_msg.toPlainText()))) if hasattr(self, 'ctc_button'): self.ctc_button.setText(_('Copied')) def toggle_det_msg(self, *args): - vis = unicode_type(self.det_msg_toggle.text()) == self.hide_det_msg + vis = str(self.det_msg_toggle.text()) == self.hide_det_msg self.det_msg_toggle.setText(self.show_det_msg if vis else self.hide_det_msg) self.det_msg.setVisible(not vis) diff --git a/src/calibre/gui2/dialogs/metadata_bulk.py b/src/calibre/gui2/dialogs/metadata_bulk.py index a5df896a98..50454e567b 100644 --- a/src/calibre/gui2/dialogs/metadata_bulk.py +++ b/src/calibre/gui2/dialogs/metadata_bulk.py @@ -33,7 +33,7 @@ from calibre.utils.date import internal_iso_format_string, qt_to_dt from calibre.utils.icu import capitalize, sort_key from calibre.utils.titlecase import titlecase -from polyglot.builtins import error_message, iteritems, itervalues, native_string_type, unicode_type +from polyglot.builtins import error_message, iteritems, itervalues, native_string_type Settings = namedtuple('Settings', 'remove_all remove add au aus do_aus rating pub do_series do_autonumber ' @@ -173,7 +173,7 @@ def do_it(self): except Exception as err: import traceback try: - err = unicode_type(err) + err = str(err) except: err = repr(err) self.error = (err, traceback.format_exc()) @@ -498,7 +498,7 @@ def __init__(self, window, rows, model, tab, refresh_books): self.refresh_book_list.toggled.connect(self.save_refresh_booklist) self.ids = [self.db.id(r) for r in rows] self.first_title = self.db.title(self.ids[0], index_is_id=True) - self.cover_clone.setToolTip(unicode_type(self.cover_clone.toolTip()) + ' (%s)' % self.first_title) + self.cover_clone.setToolTip(str(self.cover_clone.toolTip()) + ' (%s)' % self.first_title) self.setWindowTitle(ngettext( 'Editing metadata for one book', 'Editing metadata for {} books', len(rows)).format(len(rows))) @@ -596,8 +596,8 @@ def set_comments(self): self.comments = d.textbox.html b = self.comments_button b.setStyleSheet('QPushButton { font-weight: bold }') - if unicode_type(b.text())[-1] != '*': - b.setText(unicode_type(b.text()) + ' *') + if str(b.text())[-1] != '*': + b.setText(str(b.text()) + ' *') def save_refresh_booklist(self, *args): gprefs['refresh_book_list_on_bulk_edit'] = bool(self.refresh_book_list.isChecked()) @@ -767,18 +767,18 @@ def prepare_search_and_replace(self): def s_r_sf_itemdata(self, idx): if idx is None: idx = self.search_field.currentIndex() - return unicode_type(self.search_field.itemData(idx) or '') + return str(self.search_field.itemData(idx) or '') def s_r_df_itemdata(self, idx): if idx is None: idx = self.destination_field.currentIndex() - return unicode_type(self.destination_field.itemData(idx) or '') + return str(self.destination_field.itemData(idx) or '') def s_r_get_field(self, mi, field): if field: if field == '{template}': v = SafeFormat().safe_format( - unicode_type(self.s_r_template.text()), mi, _('S/R TEMPLATE ERROR'), mi) + str(self.s_r_template.text()), mi, _('S/R TEMPLATE ERROR'), mi) return [v] fm = self.db.metadata_for_field(field) if field == 'sort': @@ -788,10 +788,10 @@ def s_r_get_field(self, mi, field): else: val = mi.get(field, None) if isinstance(val, (numbers.Number, bool)): - val = unicode_type(val) + val = str(val) elif fm['is_csp']: # convert the csp dict into a list - id_type = unicode_type(self.s_r_src_ident.currentText()) + id_type = str(self.s_r_src_ident.currentText()) if id_type: val = [val.get(id_type, '')] else: @@ -840,7 +840,7 @@ def s_r_search_field_changed(self, idx): if len(t) > 1: t = t[self.starting_from.value()-1: self.starting_from.value()-1 + self.results_count.value()] - w.setText(unicode_type(self.multiple_separator.text()).join(t)) + w.setText(str(self.multiple_separator.text()).join(t)) if self.search_mode.currentIndex() == 0: self.destination_field.setCurrentIndex(idx) @@ -905,8 +905,8 @@ def s_r_set_colors(self): getattr(self, 'book_%d_result'%(i+1)).setText('') def s_r_func(self, match): - rfunc = self.s_r_functions[unicode_type(self.replace_func.currentText())] - rtext = unicode_type(self.replace_with.text()) + rfunc = self.s_r_functions[str(self.replace_func.currentText())] + rtext = str(self.replace_with.text()) rtext = match.expand(rtext) return rfunc(rtext) @@ -914,7 +914,7 @@ def s_r_do_regexp(self, mi): src_field = self.s_r_sf_itemdata(None) src = self.s_r_get_field(mi, src_field) result = [] - rfunc = self.s_r_functions[unicode_type(self.replace_func.currentText())] + rfunc = self.s_r_functions[str(self.replace_func.currentText())] for s in src: t = self.s_r_obj.sub(self.s_r_func, s) if self.search_mode.currentIndex() == 0: @@ -948,7 +948,7 @@ def s_r_do_destination(self, mi, val): dest_mode = self.replace_mode.currentIndex() if self.destination_field_fm['is_csp']: - dest_ident = unicode_type(self.s_r_dst_ident.text()) + dest_ident = str(self.s_r_dst_ident.text()) if not dest_ident or (src == 'identifiers' and dest_ident == '*'): raise Exception(_('You must specify a destination identifier type')) @@ -965,7 +965,7 @@ def s_r_do_destination(self, mi, val): if dest_mode != 0: dest_val = mi.get(dest, '') if self.db.metadata_for_field(dest)['is_csp']: - dst_id_type = unicode_type(self.s_r_dst_ident.text()) + dst_id_type = str(self.s_r_dst_ident.text()) if dst_id_type: dest_val = [dest_val.get(dst_id_type, '')] else: @@ -998,7 +998,7 @@ def s_r_paint_results(self, txt): flags |= regex.IGNORECASE try: - stext = unicode_type(self.search_for.text()) + stext = str(self.search_for.text()) if not stext: raise Exception(_('You must specify a search expression in the "Search for" field')) if self.search_mode.currentIndex() == 0: @@ -1034,7 +1034,7 @@ def s_r_paint_results(self, txt): if len(t) > 1 and self.destination_field_fm['is_multiple']: t = t[self.starting_from.value()-1: self.starting_from.value()-1 + self.results_count.value()] - t = unicode_type(self.multiple_separator.text()).join(t) + t = str(self.multiple_separator.text()).join(t) else: t = self.s_r_replace_mode_separator().join(t) wr.setText(t) @@ -1058,7 +1058,7 @@ def do_search_replace(self, book_id): if dfm['is_csp']: # convert the colon-separated pair strings back into a dict, # which is what set_identifiers wants - dst_id_type = unicode_type(self.s_r_dst_ident.text()) + dst_id_type = str(self.s_r_dst_ident.text()) if dst_id_type and dst_id_type != '*': v = ''.join(val) ids = mi.get(dest) @@ -1186,19 +1186,19 @@ def accept(self): remove_all = self.remove_all_tags.isChecked() remove = [] if not remove_all: - remove = unicode_type(self.remove_tags.text()).strip().split(',') - add = unicode_type(self.tags.text()).strip().split(',') - au = unicode_type(self.authors.text()) - aus = unicode_type(self.author_sort.text()) + remove = str(self.remove_tags.text()).strip().split(',') + add = str(self.tags.text()).strip().split(',') + au = str(self.authors.text()) + aus = str(self.author_sort.text()) do_aus = self.author_sort.isEnabled() rating = self.rating.rating_value if not self.apply_rating.isChecked(): rating = -1 - pub = unicode_type(self.publisher.text()) + pub = str(self.publisher.text()) do_series = self.write_series clear_series = self.clear_series.isChecked() clear_pub = self.clear_pub.isChecked() - series = unicode_type(self.series.currentText()).strip() + series = str(self.series.currentText()).strip() do_autonumber = self.autonumber_series.isChecked() do_series_restart = self.series_numbering_restarts.isChecked() series_start_value = self.series_start_number.value() @@ -1278,7 +1278,7 @@ def accept(self): return QDialog.accept(self) def series_changed(self, *args): - self.write_series = bool(unicode_type(self.series.currentText()).strip()) + self.write_series = bool(str(self.series.currentText()).strip()) self.autonumber_series.setEnabled(True) def s_r_remove_query(self, *args): @@ -1291,7 +1291,7 @@ def s_r_remove_query(self, *args): return item_id = self.query_field.currentIndex() - item_name = unicode_type(self.query_field.currentText()) + item_name = str(self.query_field.currentText()) self.query_field.blockSignals(True) self.query_field.removeItem(item_id) @@ -1319,7 +1319,7 @@ def s_r_save_query(self, *args): error_dialog(self, _("Save search/replace"), _("You must provide a name."), show=True) new = True - name = unicode_type(name) + name = str(name) if name in list(self.queries.keys()): if not question_dialog(self, _("Save search/replace"), _("That saved search/replace already exists and will be overwritten. " @@ -1329,21 +1329,21 @@ def s_r_save_query(self, *args): query = {} query['name'] = name - query['search_field'] = unicode_type(self.search_field.currentText()) - query['search_mode'] = unicode_type(self.search_mode.currentText()) - query['s_r_template'] = unicode_type(self.s_r_template.text()) - query['s_r_src_ident'] = unicode_type(self.s_r_src_ident.currentText()) - query['search_for'] = unicode_type(self.search_for.text()) + query['search_field'] = str(self.search_field.currentText()) + query['search_mode'] = str(self.search_mode.currentText()) + query['s_r_template'] = str(self.s_r_template.text()) + query['s_r_src_ident'] = str(self.s_r_src_ident.currentText()) + query['search_for'] = str(self.search_for.text()) query['case_sensitive'] = self.case_sensitive.isChecked() - query['replace_with'] = unicode_type(self.replace_with.text()) - query['replace_func'] = unicode_type(self.replace_func.currentText()) - query['destination_field'] = unicode_type(self.destination_field.currentText()) - query['s_r_dst_ident'] = unicode_type(self.s_r_dst_ident.text()) - query['replace_mode'] = unicode_type(self.replace_mode.currentText()) + query['replace_with'] = str(self.replace_with.text()) + query['replace_func'] = str(self.replace_func.currentText()) + query['destination_field'] = str(self.destination_field.currentText()) + query['s_r_dst_ident'] = str(self.s_r_dst_ident.text()) + query['replace_mode'] = str(self.replace_mode.currentText()) query['comma_separated'] = self.comma_separated.isChecked() query['results_count'] = self.results_count.value() query['starting_from'] = self.starting_from.value() - query['multiple_separator'] = unicode_type(self.multiple_separator.text()) + query['multiple_separator'] = str(self.multiple_separator.text()) self.queries[name] = query self.queries.commit() @@ -1362,7 +1362,7 @@ def s_r_query_change(self, item_name): self.s_r_reset_query_fields() self.saved_search_name = '' return - item = self.queries.get(unicode_type(item_name), None) + item = self.queries.get(str(item_name), None) if item is None: self.s_r_reset_query_fields() return diff --git a/src/calibre/gui2/dialogs/opml.py b/src/calibre/gui2/dialogs/opml.py index 23996fbc90..558c2e5b3c 100644 --- a/src/calibre/gui2/dialogs/opml.py +++ b/src/calibre/gui2/dialogs/opml.py @@ -17,7 +17,6 @@ from calibre.gui2 import choose_files, error_dialog from calibre.utils.xml_parse import safe_xml_fromstring from calibre.utils.icu import sort_key -from polyglot.builtins import unicode_type Group = namedtuple('Group', 'title feeds') @@ -126,7 +125,7 @@ def choose_file(self): self.path.setText(opml_files[0]) def accept(self): - path = unicode_type(self.path.text()) + path = str(self.path.text()) if not path: return error_dialog(self, _('Path not specified'), _( 'You must specify the path to the OPML file to import'), show=True) diff --git a/src/calibre/gui2/dialogs/password.py b/src/calibre/gui2/dialogs/password.py index 134ec669cf..9c59d82b27 100644 --- a/src/calibre/gui2/dialogs/password.py +++ b/src/calibre/gui2/dialogs/password.py @@ -8,7 +8,6 @@ from calibre.gui2.dialogs.password_ui import Ui_Dialog from calibre.gui2 import dynamic -from polyglot.builtins import unicode_type class PasswordDialog(QDialog, Ui_Dialog): @@ -38,12 +37,12 @@ def toggle_password(self, state): self.gui_password.setEchoMode(QLineEdit.EchoMode.Normal) def username(self): - return unicode_type(self.gui_username.text()) + return str(self.gui_username.text()) def password(self): - return unicode_type(self.gui_password.text()) + return str(self.gui_password.text()) def accept(self): - dynamic.set(self.cfg_key+'__un', unicode_type(self.gui_username.text())) - dynamic.set(self.cfg_key+'__pw', unicode_type(self.gui_password.text())) + dynamic.set(self.cfg_key+'__un', str(self.gui_username.text())) + dynamic.set(self.cfg_key+'__pw', str(self.gui_password.text())) QDialog.accept(self) diff --git a/src/calibre/gui2/dialogs/plugin_updater.py b/src/calibre/gui2/dialogs/plugin_updater.py index 09369b45c2..1b37b619fb 100644 --- a/src/calibre/gui2/dialogs/plugin_updater.py +++ b/src/calibre/gui2/dialogs/plugin_updater.py @@ -29,7 +29,7 @@ from calibre.gui2.preferences.plugins import ConfigWidget from calibre.utils.date import UNDEFINED_DATE, format_date from calibre.utils.https import get_https_resource_securely -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues SERVER = 'https://code.calibre-ebook.com/plugins/' INDEX_URL = '%splugins.json.bz2' % SERVER @@ -258,7 +258,7 @@ def set_filter_criteria(self, filter_value): self.invalidateFilter() def set_filter_text(self, filter_text_value): - self.filter_text = icu_lower(unicode_type(filter_text_value)) + self.filter_text = icu_lower(str(filter_text_value)) self.invalidateFilter() @@ -267,7 +267,7 @@ class DisplayPluginModel(QAbstractTableModel): def __init__(self, display_plugins): QAbstractTableModel.__init__(self) self.display_plugins = display_plugins - self.headers = list(map(unicode_type, [_('Plugin name'), _('Donate'), _('Status'), _('Installed'), + self.headers = list(map(str, [_('Plugin name'), _('Donate'), _('Status'), _('Installed'), _('Available'), _('Released'), _('calibre'), _('Author')])) def rowCount(self, *args): @@ -348,7 +348,7 @@ def _get_display_release_date(self, date_value, format='dd MMM yyyy'): def _get_display_version(self, version): if version is None: return '' - return '.'.join([unicode_type(v) for v in list(version)]) + return '.'.join([str(v) for v in list(version)]) def _get_status(self, display_plugin): if not display_plugin.is_valid_platform(): @@ -713,7 +713,7 @@ def _install_clicked(self): plugin = add_plugin(zip_path) except NameConflict as e: return error_dialog(self.gui, _('Already exists'), - unicode_type(e), show=True) + str(e), show=True) # Check for any toolbars to add to. widget = ConfigWidget(self.gui) widget.gui = self.gui diff --git a/src/calibre/gui2/dialogs/progress.py b/src/calibre/gui2/dialogs/progress.py index 778795336c..9aed79ec4d 100644 --- a/src/calibre/gui2/dialogs/progress.py +++ b/src/calibre/gui2/dialogs/progress.py @@ -11,7 +11,6 @@ from calibre.gui2 import elided_text from calibre.gui2.progress_indicator import ProgressIndicator -from polyglot.builtins import unicode_type class ProgressDialog(QDialog): @@ -102,7 +101,7 @@ def title(self): @title.setter def title(self, val): - self.title_label.setText(unicode_type(val or '')) + self.title_label.setText(str(val or '')) @property def msg(self): @@ -110,7 +109,7 @@ def msg(self): @msg.setter def msg(self, val): - val = unicode_type(val or '') + val = str(val or '') self.message.setText(elided_text(val, self.font(), self.message.minimumWidth()-10)) def _canceled(self, *args): diff --git a/src/calibre/gui2/dialogs/quickview.py b/src/calibre/gui2/dialogs/quickview.py index 84a455c327..f2bceb58f9 100644 --- a/src/calibre/gui2/dialogs/quickview.py +++ b/src/calibre/gui2/dialogs/quickview.py @@ -20,7 +20,6 @@ from calibre.utils.date import timestampfromdt from calibre.utils.icu import sort_key from calibre.utils.iso8601 import UNDEFINED_DATE -from polyglot.builtins import unicode_type class TableItem(QTableWidgetItem): @@ -51,7 +50,7 @@ def __ge__(self, other): # self is not None and other is None therefore self >= other return True - if isinstance(self.sort, (bytes, unicode_type)): + if isinstance(self.sort, (bytes, str)): l = sort_key(self.sort) r = sort_key(other.sort) else: @@ -76,7 +75,7 @@ def __lt__(self, other): # self is not None therefore self > other return False - if isinstance(self.sort, (bytes, unicode_type)): + if isinstance(self.sort, (bytes, str)): l = sort_key(self.sort) r = sort_key(other.sort) else: @@ -483,7 +482,7 @@ def book_was_changed(self, mi): def item_selected(self, txt): if self.no_valid_items: return - self.fill_in_books_box(unicode_type(txt)) + self.fill_in_books_box(str(txt)) self.set_search_text(self.current_key + ':"=' + txt.replace('"', '\\"') + '"') def vl_box_changed(self): @@ -569,9 +568,9 @@ def _refresh(self, book_id, key): self.no_valid_items = False if self.fm[key]['datatype'] == 'rating': if self.fm[key]['display'].get('allow_half_stars', False): - vals = unicode_type(vals/2.0) + vals = str(vals/2.0) else: - vals = unicode_type(vals//2) + vals = str(vals//2) if not isinstance(vals, list): vals = [vals] vals.sort(key=sort_key) diff --git a/src/calibre/gui2/dialogs/scheduler.py b/src/calibre/gui2/dialogs/scheduler.py index be6c1fbed9..de660e34ec 100644 --- a/src/calibre/gui2/dialogs/scheduler.py +++ b/src/calibre/gui2/dialogs/scheduler.py @@ -27,7 +27,7 @@ from calibre.utils.network import internet_connected from calibre import force_unicode from calibre.utils.localization import get_lang, canonicalize_lang -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def convert_day_time_schedule(val): @@ -160,7 +160,7 @@ def initialize(self, typ=None, val=None): @property def schedule(self): - parts = [x.strip() for x in unicode_type(self.days.text()).split(',') if + parts = [x.strip() for x in str(self.days.text()).split(',') if x.strip()] try: days_of_month = tuple(map(int, parts)) @@ -456,7 +456,7 @@ def commit(self, urn=None): return True if self.account.isVisible(): - un, pw = map(unicode_type, (self.username.text(), self.password.text())) + un, pw = map(str, (self.username.text(), self.password.text())) un, pw = un.strip(), pw.strip() if not un and not pw and self.schedule.isChecked(): if not getattr(self, 'subscription_optional', False): @@ -479,8 +479,8 @@ def commit(self, urn=None): add_title_tag = self.add_title_tag.isChecked() keep_issues = '0' if self.keep_issues.isEnabled(): - keep_issues = unicode_type(self.keep_issues.value()) - custom_tags = unicode_type(self.custom_tags.text()).strip() + keep_issues = str(self.keep_issues.value()) + custom_tags = str(self.custom_tags.text()).strip() custom_tags = [x.strip() for x in custom_tags.split(',')] self.recipe_model.customize_recipe(urn, add_title_tag, custom_tags, keep_issues) return True diff --git a/src/calibre/gui2/dialogs/search.py b/src/calibre/gui2/dialogs/search.py index 15b26d5f91..c46c2674b8 100644 --- a/src/calibre/gui2/dialogs/search.py +++ b/src/calibre/gui2/dialogs/search.py @@ -20,7 +20,6 @@ from calibre.utils.config import tweaks from calibre.utils.date import now from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import unicode_type box_values = {} last_matchkind = CONTAINS_MATCH @@ -39,7 +38,7 @@ def init_dateop(cb): def current_dateop(cb): - return unicode_type(cb.itemData(cb.currentIndex()) or '') + return str(cb.itemData(cb.currentIndex()) or '') def create_msg_label(self): @@ -332,11 +331,11 @@ def save_state(self): gprefs.set('advanced_search_simple_tab_focused_field', fw.objectName()) elif self.tab_widget.currentIndex() == 3: gprefs.set('advanced_search_template_tab_program_field', - unicode_type(self.template_program_box.text())) + str(self.template_program_box.text())) gprefs.set('advanced_search_template_tab_value_field', - unicode_type(self.template_value_box.text())) + str(self.template_value_box.text())) gprefs.set('advanced_search_template_tab_test_field', - unicode_type(self.template_test_type_box.currentIndex())) + str(self.template_test_type_box.currentIndex())) def accept(self): self.save_state() @@ -374,17 +373,17 @@ def search_string(self): self.date_search_string, self.template_search_string)[i]() def template_search_string(self): - template = unicode_type(self.template_program_box.text()) - value = unicode_type(self.template_value_box.text()).replace('"', '\\"') + template = str(self.template_program_box.text()) + value = str(self.template_value_box.text()).replace('"', '\\"') if template and value: cb = self.template_test_type_box - op = unicode_type(cb.itemData(cb.currentIndex())) + op = str(cb.itemData(cb.currentIndex())) l = '{0}#@#:{1}:{2}'.format(template, op, value) return 'template:"' + l + '"' return '' def date_search_string(self): - field = unicode_type(self.date_field.itemData(self.date_field.currentIndex()) or '') + field = str(self.date_field.itemData(self.date_field.currentIndex()) or '') op = current_dateop(self.dateop_date) prefix = '%s:%s' % (field, op) if self.sel_date.isChecked(): @@ -400,7 +399,7 @@ def date_search_string(self): val = self.date_daysago.value() val *= {0:1, 1:7, 2:30, 3:365}[self.date_ago_type.currentIndex()] return '%s%sdaysago' % (prefix, val) - return '%s%s' % (prefix, unicode_type(self.date_human.itemData(self.date_human.currentIndex()) or '')) + return '%s%s' % (prefix, str(self.date_human.itemData(self.date_human.currentIndex()) or '')) def adv_search_string(self): mk = self.matchkind.currentIndex() @@ -410,7 +409,7 @@ def adv_search_string(self): self.mc = '=' else: self.mc = '~' - all, any, phrase, none = map(lambda x: unicode_type(x.text()), + all, any, phrase, none = map(lambda x: str(x.text()), (self.all, self.any, self.phrase, self.none)) all, any, none = map(self.tokens, (all, any, none)) phrase = phrase.strip() @@ -432,11 +431,11 @@ def adv_search_string(self): return ans def token(self): - txt = unicode_type(self.text.text()).strip() + txt = str(self.text.text()).strip() if txt: if self.negate.isChecked(): txt = '!'+txt - tok = self.FIELDS[unicode_type(self.field.currentText())]+txt + tok = self.FIELDS[str(self.field.currentText())]+txt if re.search(r'\s', tok): tok = '"%s"'%tok return tok @@ -452,35 +451,35 @@ def box_search_string(self): ans = [] self.box_last_values = {} - title = unicode_type(self.title_box.text()).strip() + title = str(self.title_box.text()).strip() self.box_last_values['title_box'] = title if title: ans.append('title:"' + self.mc + title + '"') - author = unicode_type(self.authors_box.text()).strip() + author = str(self.authors_box.text()).strip() self.box_last_values['authors_box'] = author if author: ans.append('author:"' + self.mc + author + '"') - series = unicode_type(self.series_box.text()).strip() + series = str(self.series_box.text()).strip() self.box_last_values['series_box'] = series if series: ans.append('series:"' + self.mc + series + '"') - tags = unicode_type(self.tags_box.text()) + tags = str(self.tags_box.text()) self.box_last_values['tags_box'] = tags tags = [t.strip() for t in tags.split(',') if t.strip()] if tags: tags = ['tags:"' + self.mc + t + '"' for t in tags] ans.append('(' + ' or '.join(tags) + ')') - general = unicode_type(self.general_box.text()) + general = str(self.general_box.text()) self.box_last_values['general_box'] = general - general_index = unicode_type(self.general_combo.currentText()) + general_index = str(self.general_combo.currentText()) self.box_last_values['general_index'] = general_index global box_values global last_matchkind box_values = copy.deepcopy(self.box_last_values) last_matchkind = mk if general: - ans.append(unicode_type(self.general_combo.currentText()) + ':"' + + ans.append(str(self.general_combo.currentText()) + ':"' + self.mc + general + '"') if ans: return ' and '.join(ans) diff --git a/src/calibre/gui2/dialogs/smartdevice.py b/src/calibre/gui2/dialogs/smartdevice.py index 8b7cdc4aa7..aa15fb96ba 100644 --- a/src/calibre/gui2/dialogs/smartdevice.py +++ b/src/calibre/gui2/dialogs/smartdevice.py @@ -9,7 +9,7 @@ from calibre.gui2 import error_dialog from calibre.gui2.dialogs.smartdevice_ui import Ui_Dialog from calibre.utils.mdns import get_all_ips -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues def ipaddr_sort_key(ipaddr): @@ -107,7 +107,7 @@ def toggle_password(self, state): Qt.CheckState.Unchecked else QLineEdit.EchoMode.Normal) def accept(self): - port = unicode_type(self.fixed_port.text()) + port = str(self.fixed_port.text()) if not port: error_dialog(self, _('Invalid port number'), _('You must provide a port number.'), show=True) @@ -125,13 +125,13 @@ def accept(self): return self.device_manager.set_option('smartdevice', 'password', - unicode_type(self.password_box.text())) + str(self.password_box.text())) self.device_manager.set_option('smartdevice', 'autostart', self.autostart_box.isChecked()) self.device_manager.set_option('smartdevice', 'use_fixed_port', self.use_fixed_port.isChecked()) self.device_manager.set_option('smartdevice', 'port_number', - unicode_type(self.fixed_port.text())) + str(self.fixed_port.text())) message = self.device_manager.start_plugin('smartdevice') diff --git a/src/calibre/gui2/dialogs/tag_categories.py b/src/calibre/gui2/dialogs/tag_categories.py index 2efd5c269b..e0fe3e6a85 100644 --- a/src/calibre/gui2/dialogs/tag_categories.py +++ b/src/calibre/gui2/dialogs/tag_categories.py @@ -11,7 +11,7 @@ from calibre.gui2 import error_dialog, warning_dialog from calibre.constants import islinux from calibre.utils.icu import sort_key, strcmp, primary_contains -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class Item: @@ -230,7 +230,7 @@ def unapply_tags(self, node=None): def add_category(self): self.save_category() - cat_name = unicode_type(self.input_box.text()).strip() + cat_name = str(self.input_box.text()).strip() if cat_name == '': return False comps = [c.strip() for c in cat_name.split('.') if c.strip()] @@ -259,7 +259,7 @@ def add_category(self): def rename_category(self): self.save_category() - cat_name = unicode_type(self.input_box.text()).strip() + cat_name = str(self.input_box.text()).strip() if cat_name == '': return False if not self.current_cat_name: @@ -300,7 +300,7 @@ def select_category(self, idx): self.save_category() s = self.category_box.itemText(idx) if s: - self.current_cat_name = unicode_type(s) + self.current_cat_name = str(s) else: self.current_cat_name = None self.fill_applied_items() diff --git a/src/calibre/gui2/dialogs/tag_editor.py b/src/calibre/gui2/dialogs/tag_editor.py index 75f2837424..36da31dee7 100644 --- a/src/calibre/gui2/dialogs/tag_editor.py +++ b/src/calibre/gui2/dialogs/tag_editor.py @@ -10,7 +10,6 @@ from calibre.gui2 import question_dialog, error_dialog, gprefs from calibre.constants import islinux from calibre.utils.icu import sort_key, primary_contains -from polyglot.builtins import unicode_type class TagEditor(QDialog, Ui_TagEditor): @@ -125,15 +124,15 @@ def delete_tags(self, item=None): return pos = self.available_tags.verticalScrollBar().value() for item in items: - used = self.db.is_tag_used(unicode_type(item.text())) \ + used = self.db.is_tag_used(str(item.text())) \ if self.key is None else \ - self.db.is_item_used_in_multiple(unicode_type(item.text()), label=self.key) + self.db.is_item_used_in_multiple(str(item.text()), label=self.key) if used: confirms.append(item) else: deletes.append(item) if confirms: - ct = ', '.join([unicode_type(item.text()) for item in confirms]) + ct = ', '.join([str(item.text()) for item in confirms]) if question_dialog(self, _('Are your sure?'), '

    '+_('The following tags are used by one or more books. ' 'Are you certain you want to delete them?')+'
    '+ct): @@ -141,9 +140,9 @@ def delete_tags(self, item=None): for item in deletes: if self.key is None: - self.db.delete_tag(unicode_type(item.text())) + self.db.delete_tag(str(item.text())) else: - bks = self.db.delete_item_from_multiple(unicode_type(item.text()), + bks = self.db.delete_item_from_multiple(str(item.text()), label=self.key) self.db.refresh_ids(bks) self.available_tags.takeItem(self.available_tags.row(item)) @@ -161,7 +160,7 @@ def apply_tags(self, item=None): row = max(rows) tags = self._get_applied_tags_box_contents() for item in items: - tag = unicode_type(item.text()) + tag = str(item.text()) tags.append(tag) self.available_tags.takeItem(self.available_tags.row(item)) @@ -184,14 +183,14 @@ def apply_tags(self, item=None): def _get_applied_tags_box_contents(self): tags = [] for i in range(0, self.applied_tags.count()): - tags.append(unicode_type(self.applied_tags.item(i).text())) + tags.append(str(self.applied_tags.item(i).text())) return tags def unapply_tags(self, item=None): tags = self._get_applied_tags_box_contents() items = self.applied_tags.selectedItems() if item is None else [item] for item in items: - tag = unicode_type(item.text()) + tag = str(item.text()) tags.remove(tag) self.available_tags.addItem(tag) @@ -201,7 +200,7 @@ def unapply_tags(self, item=None): for tag in tags: self.applied_tags.addItem(tag) - items = [unicode_type(self.available_tags.item(x).text()) for x in + items = [str(self.available_tags.item(x).text()) for x in range(self.available_tags.count())] items.sort(key=sort_key) self.available_tags.clear() @@ -213,7 +212,7 @@ def unapply_tags(self, item=None): self.filter_tags(self.available_filter_input.text()) def add_tag(self): - tags = unicode_type(self.add_tag_input.text()).split(self.sep) + tags = str(self.add_tag_input.text()).split(self.sep) tags_in_box = self._get_applied_tags_box_contents() for tag in tags: tag = tag.strip() @@ -237,10 +236,10 @@ def add_tag(self): # filter tags def filter_tags(self, filter_value, which='available_tags'): collection = getattr(self, which) - q = icu_lower(unicode_type(filter_value)) + q = icu_lower(str(filter_value)) for i in range(collection.count()): # on every available tag item = collection.item(i) - item.setHidden(bool(q and not primary_contains(q, unicode_type(item.text())))) + item.setHidden(bool(q and not primary_contains(q, str(item.text())))) def accept(self): self.tags = self._get_applied_tags_box_contents() diff --git a/src/calibre/gui2/dialogs/tag_list_editor.py b/src/calibre/gui2/dialogs/tag_list_editor.py index 9ee9f9fbdb..0d11c83c33 100644 --- a/src/calibre/gui2/dialogs/tag_list_editor.py +++ b/src/calibre/gui2/dialogs/tag_list_editor.py @@ -18,7 +18,6 @@ from calibre.utils.config import prefs from calibre.utils.icu import contains, primary_contains, primary_startswith, capitalize from calibre.utils.titlecase import titlecase -from polyglot.builtins import unicode_type QT_HIDDEN_CLEAR_ACTION = '_q_qlineeditclearaction' @@ -84,18 +83,18 @@ def reset_placeholder(self): self.setText(self.text_before_placeholder) def __ge__(self, other): - return (self.sort_key(unicode_type(self.text())) >= - self.sort_key(unicode_type(other.text()))) + return (self.sort_key(str(self.text())) >= + self.sort_key(str(other.text()))) def __lt__(self, other): - return (self.sort_key(unicode_type(self.text())) < - self.sort_key(unicode_type(other.text()))) + return (self.sort_key(str(self.text())) < + self.sort_key(str(other.text()))) class CountTableWidgetItem(QTableWidgetItem): def __init__(self, count): - QTableWidgetItem.__init__(self, unicode_type(count)) + QTableWidgetItem.__init__(self, str(count)) self._count = count def __ge__(self, other): @@ -295,11 +294,11 @@ def show_context_menu(self, point): ca = m.addAction(_('Delete')) ca.setIcon(QIcon(I('trash.png'))) ca.triggered.connect(self.delete_tags) - item_name = unicode_type(item.text()) + item_name = str(item.text()) ca = m.addAction(_('Search for {}').format(item_name)) ca.setIcon(QIcon(I('search.png'))) ca.triggered.connect(partial(self.set_search_text, item_name)) - item_name = unicode_type(item.text()) + item_name = str(item.text()) ca = m.addAction(_('Filter by {}').format(item_name)) ca.setIcon(QIcon(I('filter.png'))) ca.triggered.connect(partial(self.set_filter_text, item_name)) @@ -329,7 +328,7 @@ def show_context_menu(self, point): def search_for_books(self, item): from calibre.gui2.ui import get_gui get_gui().search.set_search_string('{0}:"={1}"'.format(self.category, - unicode_type(item.text()).replace(r'"', r'\"'))) + str(item.text()).replace(r'"', r'\"'))) qv = get_quickview_action_plugin() if qv: @@ -343,7 +342,7 @@ def search_for_books(self, item): def copy_to_clipboard(self, item): cb = QApplication.clipboard() - cb.setText(unicode_type(item.text())) + cb.setText(str(item.text())) def paste_from_clipboard(self, item): cb = QApplication.clipboard() @@ -359,7 +358,7 @@ def do_case(self, func): # block signals to avoid the "edit one changes all" behavior self.table.blockSignals(True) for item in items: - item.setText(func(unicode_type(item.text()))) + item.setText(func(str(item.text()))) self.table.blockSignals(False) def swap_case(self, txt): @@ -371,7 +370,7 @@ def vl_box_changed(self): def do_search(self): self.not_found_label.setVisible(False) - find_text = unicode_type(self.search_box.currentText()) + find_text = str(self.search_box.currentText()) if not find_text: return for _ in range(0, self.table.rowCount()): @@ -398,7 +397,7 @@ def set_search_text(self, txt): def fill_in_table(self, tags, tag_to_match, ttm_is_first_letter): data = self.get_book_ids(self.apply_vl_checkbox.isChecked()) self.all_tags = {} - filter_text = icu_lower(unicode_type(self.filter_box.text())) + filter_text = icu_lower(str(self.filter_box.text())) for k,v,count in data: if not filter_text or self.string_contains(filter_text, icu_lower(v)): self.all_tags[v] = {'key': k, 'count': count, 'cur_name': v, @@ -435,7 +434,7 @@ def fill_in_table(self, tags, tag_to_match, ttm_is_first_letter): item.setText(self.to_rename[_id]) else: item.setText(tag) - if self.is_enumerated and unicode_type(item.text()) not in self.enum_permitted_values: + if self.is_enumerated and str(item.text()) not in self.enum_permitted_values: item.setBackground(QColor('#FF2400')) item.setToolTip( '

    ' + @@ -540,7 +539,7 @@ def finish_editing(self, edited_item): edited_item.setText(self.text_before_editing) self.table.blockSignals(False) return - new_text = unicode_type(edited_item.text()) + new_text = str(edited_item.text()) if self.is_enumerated and new_text not in self.enum_permitted_values: error_dialog(self, _('Item is not a permitted value'), '

    ' + _( "This column has a fixed set of permitted values. The entered " @@ -626,7 +625,7 @@ def delete_tags(self): to_del.append(item) if to_del: - ct = ', '.join([unicode_type(item.text()) for item in to_del]) + ct = ', '.join([str(item.text()) for item in to_del]) if not confirm( '

    '+_('Are you sure you want to delete the following items?')+'
    '+ct, 'tag_list_editor_delete'): diff --git a/src/calibre/gui2/dialogs/template_dialog.py b/src/calibre/gui2/dialogs/template_dialog.py index 38af32245c..f0e61cb456 100644 --- a/src/calibre/gui2/dialogs/template_dialog.py +++ b/src/calibre/gui2/dialogs/template_dialog.py @@ -6,7 +6,6 @@ __license__ = 'GPL v3' import json, os, traceback -from polyglot.builtins import unicode_type from qt.core import (Qt, QDialog, QDialogButtonBox, QSyntaxHighlighter, QFont, QRegExp, QApplication, QTextCharFormat, QColor, QCursor, @@ -159,7 +158,7 @@ def highlightBlock(self, text): i = regex.indexIn(text, i + length) if self.generate_paren_positions: - t = unicode_type(text) + t = str(text) i = 0 foundQuote = False while i < len(t): @@ -518,7 +517,7 @@ def save_template(self): ]) if filename: with open(filename, 'w') as f: - f.write(unicode_type(self.textbox.toPlainText())) + f.write(str(self.textbox.toPlainText())) def get_current_font(self): font_name = gprefs.get('gpm_template_editor_font', None) @@ -547,14 +546,14 @@ def set_up_font_boxes(self): self.font_box.setWritingSystem(QFontDatabase.Latin) self.font_box.setCurrentFont(font) self.font_box.setEditable(False) - gprefs['gpm_template_editor_font'] = unicode_type(font.family()) + gprefs['gpm_template_editor_font'] = str(font.family()) self.font_size_box.setValue(font.pointSize()) self.font_box.currentFontChanged.connect(self.font_changed) self.font_size_box.valueChanged.connect(self.font_size_changed) def font_changed(self, font): fi = QFontInfo(font) - gprefs['gpm_template_editor_font'] = unicode_type(fi.family()) + gprefs['gpm_template_editor_font'] = str(fi.family()) self.set_editor_font() def font_size_changed(self, toWhat): @@ -570,10 +569,10 @@ def break_box_changed(self, new_state): self.breakpoint_line_box.setEnabled(new_state != 0) self.breakpoint_line_box_label.setEnabled(new_state != 0) if new_state == 0: - self.display_values(unicode_type(self.textbox.toPlainText())) + self.display_values(str(self.textbox.toPlainText())) def go_button_pressed(self): - self.display_values(unicode_type(self.textbox.toPlainText())) + self.display_values(str(self.textbox.toPlainText())) def remove_all_button_pressed(self): self.textbox.set_clicked_line_numbers(set()) @@ -646,15 +645,15 @@ def update_filename_box(self): def color_to_clipboard(self): app = QApplication.instance() c = app.clipboard() - c.setText(unicode_type(self.color_name.color)) + c.setText(str(self.color_name.color)) def icon_to_clipboard(self): app = QApplication.instance() c = app.clipboard() - c.setText(unicode_type(self.icon_files.currentText())) + c.setText(str(self.icon_files.currentText())) def textbox_changed(self): - cur_text = unicode_type(self.textbox.toPlainText()) + cur_text = str(self.textbox.toPlainText()) if self.last_text != cur_text: self.last_text = cur_text self.highlighter.regenerate_paren_positions() @@ -681,7 +680,7 @@ def display_values(self, txt): def text_cursor_changed(self): cursor = self.textbox.textCursor() position = cursor.position() - t = unicode_type(self.textbox.toPlainText()) + t = str(self.textbox.toPlainText()) if position > 0 and position <= len(t): block_number = cursor.blockNumber() pos_in_block = cursor.positionInBlock() - 1 @@ -699,7 +698,7 @@ def function_type_string(self, name, longform=True): return (_('Stored user defined template') if longform else _('Stored template')) def function_changed(self, toWhat): - name = unicode_type(self.function.itemData(toWhat)) + name = str(self.function.itemData(toWhat)) self.source_code.clear() self.documentation.clear() self.func_type.clear() @@ -721,7 +720,7 @@ def save_geometry(self): gprefs['template_editor_dialog_geometry'] = bytearray(self.saveGeometry()) def accept(self): - txt = unicode_type(self.textbox.toPlainText()).rstrip() + txt = str(self.textbox.toPlainText()).rstrip() if (self.coloring or self.iconing or self.embleming) and not txt: error_dialog(self, _('No template provided'), _('The template box cannot be empty'), show=True) @@ -731,16 +730,16 @@ def accept(self): error_dialog(self, _('No column chosen'), _('You must specify a column to be colored'), show=True) return - self.rule = (unicode_type(self.colored_field.itemData( + self.rule = (str(self.colored_field.itemData( self.colored_field.currentIndex()) or ''), txt) elif self.iconing: if self.icon_field.currentIndex() == -1: error_dialog(self, _('No column chosen'), _('You must specify the column where the icons are applied'), show=True) return - rt = unicode_type(self.icon_kind.itemData(self.icon_kind.currentIndex()) or '') + rt = str(self.icon_kind.itemData(self.icon_kind.currentIndex()) or '') self.rule = (rt, - unicode_type(self.icon_field.itemData( + str(self.icon_field.itemData( self.icon_field.currentIndex()) or ''), txt) elif self.embleming: diff --git a/src/calibre/gui2/dialogs/template_dialog_code_widget.py b/src/calibre/gui2/dialogs/template_dialog_code_widget.py index f5ea1b225f..407857ba65 100644 --- a/src/calibre/gui2/dialogs/template_dialog_code_widget.py +++ b/src/calibre/gui2/dialogs/template_dialog_code_widget.py @@ -14,7 +14,6 @@ from calibre.gui2.tweak_book.editor.text import LineNumbers from calibre.gui2.tweak_book.editor.themes import get_theme, theme_color -from polyglot.builtins import unicode_type class LineNumberArea(LineNumbers): @@ -63,7 +62,7 @@ def update_line_number_area_width(self, block_count=0): def line_number_area_width(self): # get largest width of digits w = self.fontMetrics() - self.number_width = max(map(lambda x:w.width(unicode_type(x)), range(10))) + self.number_width = max(map(lambda x:w.width(str(x)), range(10))) digits = 1 limit = max(1, self.blockCount()) while limit >= 10: @@ -131,7 +130,7 @@ def paint_line_numbers(self, ev): else: painter.setFont(self.font()) painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(), - Qt.AlignmentFlag.AlignRight, unicode_type(num + 1)) + Qt.AlignmentFlag.AlignRight, str(num + 1)) painter.restore() block = block.next() top = bottom diff --git a/src/calibre/gui2/dnd.py b/src/calibre/gui2/dnd.py index 56efc683bf..566b403544 100644 --- a/src/calibre/gui2/dnd.py +++ b/src/calibre/gui2/dnd.py @@ -22,7 +22,6 @@ from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.filenames import make_long_path_useable from calibre.utils.imghdr import what -from polyglot.builtins import unicode_type from polyglot.queue import Empty, Queue from polyglot.urllib import unquote, urlparse @@ -198,7 +197,7 @@ def dnd_has_extension(md, extensions, allow_all_extensions=False, allow_remote=F if DEBUG: prints('\nDebugging DND event') for f in md.formats(): - f = unicode_type(f) + f = str(f) raw = data_as_string(f, md) prints(f, len(raw), repr(raw[:300]), '\n') print() @@ -221,7 +220,7 @@ def dnd_has_extension(md, extensions, allow_all_extensions=False, allow_remote=F def dnd_get_local_image_and_pixmap(md, image_exts=None): if md.hasImage(): for x in md.formats(): - x = unicode_type(x) + x = str(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() @@ -347,7 +346,7 @@ def _get_firefox_pair(md, exts, url, fname): def get_firefox_rurl(md, exts): - formats = frozenset([unicode_type(x) for x in md.formats()]) + formats = frozenset([str(x) for x in md.formats()]) url = fname = None if 'application/x-moz-file-promise-url' in formats and \ 'application/x-moz-file-promise-dest-filename' in formats: diff --git a/src/calibre/gui2/email.py b/src/calibre/gui2/email.py index b6b8f20668..87dabb3a4d 100644 --- a/src/calibre/gui2/email.py +++ b/src/calibre/gui2/email.py @@ -26,7 +26,7 @@ from calibre.utils.config import tweaks, prefs from calibre.utils.icu import primary_sort_key from calibre.gui2.threaded_jobs import ThreadedJob -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot.binary import from_hex_unicode @@ -210,7 +210,7 @@ def __init__(self, parent=None): for i, name in enumerate(('address', 'alias', 'formats', 'subject')): c = i % 2 row = l.rowCount() - c - self.labels[i].setText(unicode_type(self.labels[i].text()) + ':') + self.labels[i].setText(str(self.labels[i].text()) + ':') l.addWidget(self.labels[i], row, (2*c)) le = QLineEdit(self) le.setToolTip(tooltips[i]) @@ -232,11 +232,11 @@ def __init__(self, parent=None): self.init_list() def add_recipient(self): - to = unicode_type(self.address.text()).strip() + to = str(self.address.text()).strip() if not to: return error_dialog( self, _('Need address'), _('You must specify an address'), show=True) - formats = ','.join([x.strip().upper() for x in unicode_type(self.formats.text()).strip().split(',') if x.strip()]) + formats = ','.join([x.strip().upper() for x in str(self.formats.text()).strip().split(',') if x.strip()]) if not formats: return error_dialog( self, _('Need formats'), _('You must specify at least one format to send'), show=True) @@ -248,11 +248,11 @@ def add_recipient(self): acc[to] = [formats, False, False] c = email_config() c.set('accounts', acc) - alias = unicode_type(self.alias.text()).strip() + alias = str(self.alias.text()).strip() if alias: opts.aliases[to] = alias c.set('aliases', opts.aliases) - subject = unicode_type(self.subject.text()).strip() + subject = str(self.subject.text()).strip() if subject: opts.subjects[to] = subject c.set('subjects', opts.subjects) @@ -287,7 +287,7 @@ def ans(self): ans = [] for i in self.items: if i.checkState() == Qt.CheckState.Checked: - to = unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') + to = str(i.data(Qt.ItemDataRole.UserRole) or '') fmts = tuple(x.strip().upper() for x in (opts.accounts[to][0] or '').split(',')) subject = opts.subjects.get(to, '') ans.append((to, fmts, subject)) @@ -408,7 +408,7 @@ def send_by_mail(self, to, fmts, delete_from_library, subject='', send_ids=None, from calibre.utils.html2text import html2text texts[-1] += '\n\n' + _('About this book:') + '\n\n' + textwrap.fill(html2text(mi.comments)) prefix = f'{t} - {a}' - if not isinstance(prefix, unicode_type): + if not isinstance(prefix, str): prefix = prefix.decode(preferred_encoding, 'replace') attachment_names.append(prefix + os.path.splitext(f)[1]) remove = remove_ids if delete_from_library else [] diff --git a/src/calibre/gui2/font_family_chooser.py b/src/calibre/gui2/font_family_chooser.py index 8226f503a4..338612a594 100644 --- a/src/calibre/gui2/font_family_chooser.py +++ b/src/calibre/gui2/font_family_chooser.py @@ -16,7 +16,6 @@ from calibre.constants import config_dir from calibre.gui2 import choose_files, error_dialog, info_dialog, empty_index -from polyglot.builtins import unicode_type def add_fonts(parent): @@ -112,7 +111,7 @@ def paint(self, painter, option, index): painter.restore() def do_paint(self, painter, option, index): - text = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') + text = str(index.data(Qt.ItemDataRole.DisplayRole) or '') font = QFont(option.font) font.setPointSize(QFontInfo(font).pointSize() * 1.5) font2 = QFont(font) @@ -264,7 +263,7 @@ def find(self, backwards=False): i = self.view.currentIndex().row() if i < 0: i = 0 - q = icu_lower(unicode_type(self.search.text())).strip() + q = icu_lower(str(self.search.text())).strip() if not q: return r = (range(i-1, -1, -1) if backwards else range(i+1, diff --git a/src/calibre/gui2/icon_theme.py b/src/calibre/gui2/icon_theme.py index 20d3643548..766269215b 100644 --- a/src/calibre/gui2/icon_theme.py +++ b/src/calibre/gui2/icon_theme.py @@ -33,7 +33,7 @@ from calibre.utils.img import image_from_data, Canvas, optimize_png, optimize_jpeg from calibre.utils.zipfile import ZipFile, ZIP_STORED from calibre.utils.filenames import atomic_rename -from polyglot.builtins import iteritems, reraise, as_bytes, unicode_type +from polyglot.builtins import iteritems, reraise, as_bytes from polyglot import http_client from polyglot.queue import Queue, Empty @@ -619,7 +619,7 @@ def setup_ui(self): w.l = l = QGridLayout(w) def add_row(x, y=None): - if isinstance(x, unicode_type): + if isinstance(x, str): x = QLabel(x) row = l.rowCount() if y is None: diff --git a/src/calibre/gui2/image_popup.py b/src/calibre/gui2/image_popup.py index 9d2f11a606..bdf4c0ae8f 100644 --- a/src/calibre/gui2/image_popup.py +++ b/src/calibre/gui2/image_popup.py @@ -16,7 +16,6 @@ from calibre.gui2 import ( NO_URL_FORMATTING, choose_save_file, gprefs, max_available_height ) -from polyglot.builtins import unicode_type def render_svg(widget, path): @@ -248,7 +247,7 @@ def __call__(self, use_exec=False): if geom is not None: QApplication.instance().safe_restore_geometry(self, geom) try: - self.current_image_name = unicode_type(self.current_url.toString(NO_URL_FORMATTING)).rpartition('/')[-1] + self.current_image_name = str(self.current_url.toString(NO_URL_FORMATTING)).rpartition('/')[-1] except AttributeError: self.current_image_name = self.current_url reso = '' diff --git a/src/calibre/gui2/init.py b/src/calibre/gui2/init.py index 6de1bb2dc7..8f1789d223 100644 --- a/src/calibre/gui2/init.py +++ b/src/calibre/gui2/init.py @@ -28,7 +28,6 @@ from calibre.utils.config import prefs from calibre.utils.icu import sort_key from calibre.utils.localization import localize_website_link -from polyglot.builtins import unicode_type _keep_refs = [] @@ -338,7 +337,7 @@ def __init__(self, gui): self.set_state_to_show() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) - gui.keyboard.register_shortcut('grid view toggle' + self.label, unicode_type(self.action_toggle.text()), + gui.keyboard.register_shortcut('grid view toggle' + self.label, str(self.action_toggle.text()), default_keys=(sc,), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.action_toggle.changed.connect(self.update_shortcut) @@ -368,7 +367,7 @@ def __init__(self, gui): self.set_state_to_hide() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) - gui.keyboard.register_shortcut('search bar toggle' + self.label, unicode_type(self.action_toggle.text()), + gui.keyboard.register_shortcut('search bar toggle' + self.label, str(self.action_toggle.text()), default_keys=(sc,), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.action_toggle.changed.connect(self.update_shortcut) @@ -453,14 +452,14 @@ def unlock_tab(self): def tab_changed(self, idx): if self.ignore_tab_changed: return - vl = unicode_type(self.tabData(idx) or '').strip() or None + vl = str(self.tabData(idx) or '').strip() or None self.gui.apply_virtual_library(vl, update_tabs=False) def tab_moved(self, from_, to): - self.current_db.new_api.set_pref('virt_libs_order', [unicode_type(self.tabData(i) or '') for i in range(self.count())]) + self.current_db.new_api.set_pref('virt_libs_order', [str(self.tabData(i) or '') for i in range(self.count())]) def tab_close(self, index): - vl = unicode_type(self.tabData(index) or '') + vl = str(self.tabData(index) or '') if vl: # Dont allow closing the All Books tab self.current_db.new_api.set_pref('virt_libs_hidden', list( self.current_db.new_api.pref('virt_libs_hidden', ())) + [vl]) @@ -536,7 +535,7 @@ def contextMenuEvent(self, ev): m.addAction(_('Unlock Virtual library tabs'), self.unlock_tab) i = self.tabAt(ev.pos()) if i > -1: - vl = unicode_type(self.tabData(i) or '') + vl = str(self.tabData(i) or '') if vl: m.addSeparator() m.addAction(_('Edit "%s"') % vl, partial(self.gui.do_create_edit, name=vl)) @@ -600,7 +599,7 @@ def init_layout_mixin(self): self.qv = self.qv.actual_plugin_ self.status_bar = StatusBar(self) - stylename = unicode_type(self.style().objectName()) + stylename = str(self.style().objectName()) self.grid_view_button = GridViewButton(self) self.search_bar_button = SearchBarButton(self) self.grid_view_button.toggled.connect(self.toggle_grid_view) diff --git a/src/calibre/gui2/keyboard.py b/src/calibre/gui2/keyboard.py index 17f4fdd21e..68c07f2ce7 100644 --- a/src/calibre/gui2/keyboard.py +++ b/src/calibre/gui2/keyboard.py @@ -21,7 +21,7 @@ from calibre.gui2 import error_dialog, info_dialog from calibre.utils.search_query_parser import SearchQueryParser, ParseException from calibre.gui2.search_box import SearchBox2 -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues ROOT = QModelIndex() @@ -66,7 +66,7 @@ def finalize(shortcuts, custom_keys_map={}): # {{{ keys = [] for x in candidates: ks = QKeySequence(x, QKeySequence.SequenceFormat.PortableText) - x = unicode_type(ks.toString(QKeySequence.SequenceFormat.PortableText)) + x = str(ks.toString(QKeySequence.SequenceFormat.PortableText)) if x in seen: if DEBUG: prints('Key %r for shortcut %s is already used by' @@ -299,7 +299,7 @@ def commit(self): if sc['persist_shortcut']: options_map[un] = options_map.get(un, {}) options_map[un]['persist_shortcut'] = sc['persist_shortcut'] - keys = [unicode_type(k.toString(QKeySequence.SequenceFormat.PortableText)) for k in sc['keys']] + keys = [str(k.toString(QKeySequence.SequenceFormat.PortableText)) for k in sc['keys']] kmap[un] = keys with self.keyboard.config: self.keyboard.config['map'] = kmap @@ -447,11 +447,11 @@ def initialize(self, shortcut, all_shortcuts): self.default_keys = [QKeySequence(k, QKeySequence.SequenceFormat.PortableText) for k in shortcut['default_keys']] self.current_keys = list(shortcut['keys']) - default = ', '.join([unicode_type(k.toString(QKeySequence.SequenceFormat.NativeText)) for k in + default = ', '.join([str(k.toString(QKeySequence.SequenceFormat.NativeText)) for k in self.default_keys]) if not default: default = _('None') - current = ', '.join([unicode_type(k.toString(QKeySequence.SequenceFormat.NativeText)) for k in + current = ', '.join([str(k.toString(QKeySequence.SequenceFormat.NativeText)) for k in self.current_keys]) if not current: current = _('None') @@ -509,7 +509,7 @@ def key_press_event(self, ev, which=0): dup_desc = self.dup_check(sequence) if dup_desc is not None: error_dialog(self, _('Already assigned'), - unicode_type(sequence.toString(QKeySequence.SequenceFormat.NativeText)) + ' ' + _( + str(sequence.toString(QKeySequence.SequenceFormat.NativeText)) + ' ' + _( 'already assigned to') + ' ' + dup_desc, show=True) self.clear_clicked(which=which) @@ -528,7 +528,7 @@ def custom_keys(self): ans = [] for which in (1, 2): button = getattr(self, 'button%d'%which) - t = unicode_type(button.text()) + t = str(button.text()) if t == _('None'): continue ks = QKeySequence(t, QKeySequence.SequenceFormat.NativeText) @@ -555,7 +555,7 @@ def to_doc(self, index): elif data.is_shortcut: shortcut = data.data # Shortcut - keys = [unicode_type(k.toString(QKeySequence.SequenceFormat.NativeText)) for k in shortcut['keys']] + keys = [str(k.toString(QKeySequence.SequenceFormat.NativeText)) for k in shortcut['keys']] if not keys: keys = _('None') else: @@ -733,7 +733,7 @@ def find_next(self, *args): if not idx.isValid(): idx = self._model.index(0, 0) idx = self._model.find_next(idx, - unicode_type(self.search.currentText())) + str(self.search.currentText())) self.highlight_index(idx) def find_previous(self, *args): @@ -741,7 +741,7 @@ def find_previous(self, *args): if not idx.isValid(): idx = self._model.index(0, 0) idx = self._model.find_next(idx, - unicode_type(self.search.currentText()), backwards=True) + str(self.search.currentText()), backwards=True) self.highlight_index(idx) def highlight_group(self, group_name): diff --git a/src/calibre/gui2/languages.py b/src/calibre/gui2/languages.py index 9a878b4149..e79e4fab66 100644 --- a/src/calibre/gui2/languages.py +++ b/src/calibre/gui2/languages.py @@ -11,7 +11,7 @@ from calibre.gui2.complete2 import EditWithComplete from calibre.utils.localization import lang_map_for_ui from calibre.utils.icu import sort_key, lower -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues class LanguagesEdit(EditWithComplete): @@ -54,7 +54,7 @@ def sort_language_items_key(self, val): @property def vals(self): - raw = unicode_type(self.lineEdit().text()) + raw = str(self.lineEdit().text()) for k, v in iteritems(self.comma_map): raw = raw.replace(k, v) parts = [x.strip() for x in raw.split(',')] diff --git a/src/calibre/gui2/layout.py b/src/calibre/gui2/layout.py index fdcea95bcc..9f08dba1c1 100644 --- a/src/calibre/gui2/layout.py +++ b/src/calibre/gui2/layout.py @@ -18,7 +18,6 @@ from calibre.gui2.search_box import SavedSearchBox, SearchBox2 from calibre.gui2.widgets2 import RightClickButton from calibre.utils.config_base import tweaks -from polyglot.builtins import unicode_type class LocationManager(QObject): # {{{ @@ -129,7 +128,7 @@ def update_devices(self, cp=(None, None), fs=[-1, -1, -1], icon=None): had_device = self.has_device if cp is None: cp = (None, None) - if isinstance(cp, (bytes, unicode_type)): + if isinstance(cp, (bytes, str)): cp = (cp, None) if len(fs) < 3: fs = list(fs) + [0] diff --git a/src/calibre/gui2/library/alternate_views.py b/src/calibre/gui2/library/alternate_views.py index 4c7849d150..339359c8f7 100644 --- a/src/calibre/gui2/library/alternate_views.py +++ b/src/calibre/gui2/library/alternate_views.py @@ -31,7 +31,7 @@ from calibre.gui2.pin_columns import PinContainer from calibre.utils import join_with_timeout from calibre.utils.config import prefs, tweaks -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues from polyglot.queue import LifoQueue CM_TO_INCH = 0.393701 @@ -470,7 +470,7 @@ def render_field(self, db, book_id): if fm and fm['datatype'] == 'rating': ans = rating_to_stars(val, fm['display'].get('allow_half_stars', False)) is_stars = True - return ('' if ans is None else unicode_type(ans)), is_stars + return ('' if ans is None else str(ans)), is_stars except Exception: if DEBUG: import traceback diff --git a/src/calibre/gui2/library/delegates.py b/src/calibre/gui2/library/delegates.py index 2d30b4c5b8..f4db5a37cf 100644 --- a/src/calibre/gui2/library/delegates.py +++ b/src/calibre/gui2/library/delegates.py @@ -27,7 +27,6 @@ from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.gui2.dialogs.tag_editor import TagEditor from calibre.gui2.languages import LanguagesEdit -from polyglot.builtins import unicode_type class UpdateEditorGeometry: @@ -169,7 +168,7 @@ def get_val_for_textlike_columns(index_): ct = '' else: ct = index_.data(Qt.ItemDataRole.DisplayRole) or '' - return unicode_type(ct) + return str(ct) # }}} @@ -610,7 +609,7 @@ def createEditor(self, parent, option, index): return editor def setModelData(self, editor, model, index): - val = unicode_type(editor.currentText()) + val = str(editor.currentText()) if not val: val = None model.setData(index, (val), Qt.ItemDataRole.EditRole) diff --git a/src/calibre/gui2/library/models.py b/src/calibre/gui2/library/models.py index 854aed3d2b..efe0ca561a 100644 --- a/src/calibre/gui2/library/models.py +++ b/src/calibre/gui2/library/models.py @@ -41,7 +41,7 @@ from calibre.utils.icu import sort_key from calibre.utils.localization import calibre_langcode_to_name from calibre.utils.search_query_parser import ParseException, SearchQueryParser -from polyglot.builtins import iteritems, itervalues, string_or_bytes, unicode_type +from polyglot.builtins import iteritems, itervalues, string_or_bytes Counts = namedtuple('Counts', 'library_total total current') @@ -76,7 +76,7 @@ def __init__(self, formatter): self.formatter = formatter def __call__(self, id_, key, fmt, db, color_cache, template_cache): - key += unicode_type(hash(fmt)) + key += str(hash(fmt)) if id_ in color_cache and key in color_cache[id_]: self.mi = None color = color_cache[id_][key] @@ -117,7 +117,7 @@ def __call__(self, id_, fmts, cache_index, db, icon_cache, icon_bitmap_cache, icons = [] for dex, (kind, fmt) in enumerate(fmts): rule_icons = self.formatter.safe_format(fmt, self.mi, '', self.mi, - column_name=cache_index+unicode_type(dex), + column_name=cache_index+str(dex), template_cache=template_cache) if not rule_icons: continue @@ -890,7 +890,7 @@ def func(idx): def stars_tooltip(func, allow_half=True): def f(idx): ans = val = int(func(idx)) - ans = unicode_type(val // 2) + ans = str(val // 2) if allow_half and val % 2: ans += '.5' return _('%s stars') % ans @@ -955,7 +955,7 @@ def data(self, index, role): cc = self.custom_columns[self.column_map[col]]['display'] colors = cc.get('enum_colors', []) values = cc.get('enum_values', []) - txt = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') + txt = str(index.data(Qt.ItemDataRole.DisplayRole) or '') if len(colors) > 0 and txt in values: try: color = QColor(colors[values.index(txt)]) @@ -1075,10 +1075,10 @@ def set_custom_column_data(self, row, colhead, value): label=self.db.field_metadata.key_to_label(colhead) s_index = None if typ in ('text', 'comments'): - val = unicode_type(value or '').strip() + val = str(value or '').strip() val = val if val else None elif typ == 'enumeration': - val = unicode_type(value or '').strip() + val = str(value or '').strip() if not val: val = None elif typ == 'bool': @@ -1089,7 +1089,7 @@ def set_custom_column_data(self, row, colhead, value): if value == 0: val = '0' else: - val = unicode_type(value or '').strip() + val = str(value or '').strip() if not val: val = None elif typ == 'datetime': @@ -1101,7 +1101,7 @@ def set_custom_column_data(self, row, colhead, value): return False val = qt_to_dt(val, as_utc=False) elif typ == 'series': - val = unicode_type(value or '').strip() + val = str(value or '').strip() if val: pat = re.compile(r'\[([.0-9]+)\]') match = pat.search(val) @@ -1115,7 +1115,7 @@ def set_custom_column_data(self, row, colhead, value): s_index = self.db.get_next_cc_series_num_for(val, label=label, num=None) elif typ == 'composite': - tmpl = unicode_type(value or '').strip() + tmpl = str(value or '').strip() disp = cc['display'] disp['composite_template'] = tmpl self.db.set_custom_column_metadata(cc['colnum'], display=disp, @@ -1171,7 +1171,7 @@ def _set_data(self, index, value): return False val = (int(value) if column == 'rating' else value if column in ('timestamp', 'pubdate') - else re.sub(r'\s', ' ', unicode_type(value or '').strip())) + else re.sub(r'\s', ' ', str(value or '').strip())) id = self.db.id(row) books_to_refresh = {id} if column == 'rating': @@ -1739,7 +1739,7 @@ def setData(self, index, value, role): cname = self.column_map[col] if cname in ('size', 'timestamp', 'inlibrary'): return False - val = unicode_type(value or '').strip() + val = str(value or '').strip() idx = self.map[row] if cname == 'collections': tags = [i.strip() for i in val.split(',')] diff --git a/src/calibre/gui2/library/views.py b/src/calibre/gui2/library/views.py index 6333b8f1aa..e6e6163e8f 100644 --- a/src/calibre/gui2/library/views.py +++ b/src/calibre/gui2/library/views.py @@ -30,7 +30,7 @@ from calibre.constants import filesystem_encoding from calibre import force_unicode from calibre.utils.icu import primary_sort_key -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def restrict_column_width(self, col, old_size, new_size): @@ -74,7 +74,7 @@ def sectionSizeFromContents(self, logical_index): opt.orientation = self.orientation() opt.fontMetrics = self.fm model = self.parent().model() - opt.text = unicode_type(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '') + opt.text = str(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '') if opt.orientation == Qt.Orientation.Vertical: try: val = model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DecorationRole) @@ -102,7 +102,7 @@ def paintSection(self, painter, rect, logical_index): opt.sortIndicator = QStyleOptionHeader.SortIndicator.SortDown if \ self.sortIndicatorOrder() == Qt.SortOrder.AscendingOrder else QStyleOptionHeader.SortIndicator.SortUp margin += style.pixelMetric(QStyle.PixelMetric.PM_HeaderMarkSize, None, self) - opt.text = unicode_type(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '') + opt.text = str(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '') if self.textElideMode() != Qt.TextElideMode.ElideNone: opt.text = opt.fontMetrics.elidedText(opt.text, Qt.TextElideMode.ElideRight, rect.width() - margin) if self.isEnabled(): @@ -480,7 +480,7 @@ def create_context_menu(self, col, name, view): ans.addSeparator() if hidden_cols: m = ans.addMenu(_('Show column')) - hcols = [(hcol, unicode_type(self.model().headerData(hidx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '')) + hcols = [(hcol, str(self.model().headerData(hidx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '')) for hcol, hidx in iteritems(hidden_cols)] hcols.sort(key=lambda x: primary_sort_key(x[1])) for hcol, hname in hcols: @@ -516,7 +516,7 @@ def show_column_header_context_menu(self, pos, view=None): col = None if idx > -1 and idx < len(self.column_map): col = self.column_map[idx] - name = unicode_type(self.model().headerData(idx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '') + name = str(self.model().headerData(idx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '') view.column_header_context_menu = self.create_context_menu(col, name, view) has_context_menu = hasattr(view, 'column_header_context_menu') if self.is_library_view and has_context_menu: @@ -674,7 +674,7 @@ def get_state(self): def write_state(self, state): db = getattr(self.model(), 'db', None) - name = unicode_type(self.objectName()) + name = str(self.objectName()) if name and db is not None: db.new_api.set_pref(name + ' books view state', state) @@ -789,7 +789,7 @@ def get_default_state(self): def get_old_state(self): ans = None - name = unicode_type(self.objectName()) + name = str(self.objectName()) if name: name += ' books view state' db = getattr(self.model(), 'db', None) @@ -1428,14 +1428,14 @@ def contextMenuEvent(self, event): def get_old_state(self): ans = None - name = unicode_type(self.objectName()) + name = str(self.objectName()) if name: name += ' books view state' ans = gprefs.get(name, None) return ans def write_state(self, state): - name = unicode_type(self.objectName()) + name = str(self.objectName()) if name: gprefs.set(name + ' books view state', state) diff --git a/src/calibre/gui2/linux_file_dialogs.py b/src/calibre/gui2/linux_file_dialogs.py index a973435252..4203c490f3 100644 --- a/src/calibre/gui2/linux_file_dialogs.py +++ b/src/calibre/gui2/linux_file_dialogs.py @@ -14,7 +14,7 @@ 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, unicode_type +from polyglot.builtins import reraise, string_or_bytes def dialog_name(name, title): @@ -82,7 +82,7 @@ def save_initial_dir(name, title, ans, no_save_dir, is_file=False): def encode_arg(title): - if isinstance(title, unicode_type): + if isinstance(title, str): try: title = title.encode(preferred_encoding) except UnicodeEncodeError: @@ -136,7 +136,7 @@ def kde_cmd(window, title, *rest): ans += ['--desktopfile', 'calibre-gui'] winid = get_winid(window) if winid is not None: - ans += ['--attach', unicode_type(int(winid))] + ans += ['--attach', str(int(winid))] return ans + list(rest) diff --git a/src/calibre/gui2/lrf_renderer/document.py b/src/calibre/gui2/lrf_renderer/document.py index 749f35e1d9..ed4d1fb919 100644 --- a/src/calibre/gui2/lrf_renderer/document.py +++ b/src/calibre/gui2/lrf_renderer/document.py @@ -12,7 +12,6 @@ from calibre.gui2.lrf_renderer.text import TextBlock, FontLoader, COLOR, PixmapItem from calibre.ebooks.lrf.objects import RuledLine as _RuledLine from calibre.ebooks.lrf.objects import Canvas as __Canvas -from polyglot.builtins import unicode_type class Color(QColor): @@ -418,7 +417,7 @@ def load_fonts(self, lrf, load_substitutions=True): fdata = QByteArray(lrf.font_map[font].data) id = QFontDatabase.addApplicationFontFromData(fdata) if id != -1: - font_map[font] = [unicode_type(i) for i in QFontDatabase.applicationFontFamilies(id)][0] + font_map[font] = [str(i) for i in QFontDatabase.applicationFontFamilies(id)][0] if load_substitutions: base = P('fonts/liberation/*.ttf') diff --git a/src/calibre/gui2/lrf_renderer/text.py b/src/calibre/gui2/lrf_renderer/text.py index c9bcff1cea..6c7212a22c 100644 --- a/src/calibre/gui2/lrf_renderer/text.py +++ b/src/calibre/gui2/lrf_renderer/text.py @@ -11,7 +11,7 @@ from calibre.ebooks.lrf.fonts import LIBERATION_FONT_MAP from calibre.ebooks.hyphenate import hyphenate_word -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes WEIGHT_MAP = lambda wt : int((wt/10)-1) NULL = lambda a, b: a @@ -156,7 +156,7 @@ def __init__(self, parskip): self.height = parskip def __str__(self): - return 'Parskip: '+unicode_type(self.height) + return 'Parskip: '+str(self.height) class TextBlock: @@ -291,7 +291,7 @@ def end_line(self): self.current_style.linespace, self.opts.visual_debug) if self.height > self.max_y+10: - raise TextBlock.HeightExceeded(unicode_type(self.current_line)) + raise TextBlock.HeightExceeded(str(self.current_line)) self.lines.append(self.current_line) self.current_line = None @@ -327,7 +327,7 @@ def __iter__(self): def __str__(self): s = '' for line in self: - s += unicode_type(line) + '\n' + s += str(line) + '\n' return s @@ -542,12 +542,12 @@ def search(self, phrase): while True: word = next(words) word.highlight = False - if tokens[0] in unicode_type(word.string).lower(): + if tokens[0] in str(word.string).lower(): matches.append(word) for c in range(1, len(tokens)): word = next(words) print(tokens[c], word.string) - if tokens[c] not in unicode_type(word.string): + if tokens[c] not in str(word.string): return None matches.append(word) for w in matches: @@ -570,11 +570,11 @@ def __unicode__(self): if isinstance(tok, numbers.Number): s += ' ' elif isinstance(tok, Word): - s += unicode_type(tok.string) + s += str(tok.string) return s def __str__(self): - return unicode_type(self).encode('utf-8') + return str(self).encode('utf-8') class Word: diff --git a/src/calibre/gui2/main.py b/src/calibre/gui2/main.py index 8e0d78e48c..45feca9b6a 100644 --- a/src/calibre/gui2/main.py +++ b/src/calibre/gui2/main.py @@ -27,7 +27,7 @@ from calibre.utils.config import dynamic, prefs from calibre.utils.lock import SingleInstance from calibre.utils.monotonic import monotonic -from polyglot.builtins import as_bytes, environ_item, unicode_type +from polyglot.builtins import as_bytes, environ_item after_quit_actions = {'debug_on_restart': False, 'restart_after_quit': False, 'no_plugins_on_restart': False} if iswindows: @@ -141,7 +141,7 @@ def get_default_library_path(): fname = _('Calibre Library') if iswindows: fname = 'Calibre Library' - if isinstance(fname, unicode_type): + if isinstance(fname, str): try: fname.encode(filesystem_encoding) except Exception: @@ -170,7 +170,7 @@ def get_library_path(gui_runner): base = os.path.expanduser('~') if not base or not os.path.exists(base): from qt.core import QDir - base = unicode_type(QDir.homePath()).replace('/', os.sep) + base = str(QDir.homePath()).replace('/', os.sep) candidate = gui_runner.choose_dir(base) if not candidate: candidate = os.path.join(base, 'Calibre Library') @@ -562,6 +562,6 @@ def run_main(app, opts, args, gui_debug, si): log = f.read().decode('utf-8', 'ignore') d = QErrorMessage() d.showMessage(('Error:%s
    Traceback:
    ' - '%sLog:
    %s')%(unicode_type(err), - unicode_type(tb).replace('\n', '
    '), + '%sLog:
    %s')%(str(err), + str(tb).replace('\n', '
    '), log.replace('\n', '
    '))) diff --git a/src/calibre/gui2/metadata/basic_widgets.py b/src/calibre/gui2/metadata/basic_widgets.py index e441a06edb..275ad14c0c 100644 --- a/src/calibre/gui2/metadata/basic_widgets.py +++ b/src/calibre/gui2/metadata/basic_widgets.py @@ -50,7 +50,7 @@ ) from calibre.utils.filenames import make_long_path_useable from calibre.utils.icu import sort_key, strcmp -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def show_locked_file_error(parent, err): @@ -241,7 +241,7 @@ def commit(self, db, id_): @property def current_val(self): - title = clean_text(unicode_type(self.text())) + title = clean_text(str(self.text())) if not title: title = self.get_default() return title.strip() @@ -434,7 +434,7 @@ def commit(self, db, id_): @property def current_val(self): - au = clean_text(unicode_type(self.text())) + au = clean_text(str(self.text())) if not au: au = self.get_default() return string_to_authors(au) @@ -501,7 +501,7 @@ def __init__(self, parent, authors_edit, autogen_button, db, @property def current_val(self): - return clean_text(unicode_type(self.text())) + return clean_text(str(self.text())) @current_val.setter def current_val(self, val): @@ -522,7 +522,7 @@ def author_sort_from_authors(self, authors): return self.db.new_api.author_sort_from_authors(authors, key_func=lambda x: x) def update_state(self, *args): - au = unicode_type(self.authors_edit.text()) + au = str(self.authors_edit.text()) au = re.sub(r'\s+et al\.$', '', au) au = self.author_sort_from_authors(string_to_authors(au)) @@ -548,13 +548,13 @@ def copy_to_authors(self): self.authors_edit.set_value(ans) def auto_generate(self, *args): - au = unicode_type(self.authors_edit.text()) + au = str(self.authors_edit.text()) au = re.sub(r'\s+et al\.$', '', au).strip() authors = string_to_authors(au) self.set_value(self.author_sort_from_authors(authors)) def author_to_sort(self, *args): - au = unicode_type(self.authors_edit.text()) + au = str(self.authors_edit.text()) au = re.sub(r'\s+et al\.$', '', au).strip() if au: self.set_value(au) @@ -627,7 +627,7 @@ def __init__(self, parent): @property def current_val(self): - return clean_text(unicode_type(self.currentText())) + return clean_text(str(self.currentText())) @current_val.setter def current_val(self, val): @@ -1198,7 +1198,7 @@ def select_cover(self, *args): except IOError as e: d = error_dialog( self, _('Error reading file'), - _("

    There was an error reading from file:
    ") + _file + "


    "+unicode_type(e)) + _("

    There was an error reading from file:
    ") + _file + "


    "+str(e)) d.exec_() if cover: orig = self.current_val @@ -1406,7 +1406,7 @@ def __init__(self, parent): @property def current_val(self): - return [clean_text(x) for x in unicode_type(self.text()).split(',')] + return [clean_text(x) for x in str(self.text()).split(',')] @current_val.setter def current_val(self, val): @@ -1594,7 +1594,7 @@ def edit_identifiers(self): @property def current_val(self): - raw = unicode_type(self.text()).strip() + raw = str(self.text()).strip() parts = [clean_text(x) for x in raw.split(',')] ans = {} for x in parts: @@ -1658,7 +1658,7 @@ def paste_identifier(self): identifier_found = self.parse_clipboard_for_identifier() if identifier_found: return - text = unicode_type(QApplication.clipboard().text()).strip() + text = str(QApplication.clipboard().text()).strip() if text.startswith('http://') or text.startswith('https://'): return self.paste_prefix('url') try: @@ -1671,14 +1671,14 @@ def paste_prefix(self, prefix): if prefix == 'isbn': self.paste_isbn() else: - text = unicode_type(QApplication.clipboard().text()).strip() + text = str(QApplication.clipboard().text()).strip() if text: vals = self.current_val vals[prefix] = text self.current_val = vals def paste_isbn(self): - text = unicode_type(QApplication.clipboard().text()).strip() + text = str(QApplication.clipboard().text()).strip() if not text or not check_isbn(text): d = ISBNDialog(self, text) if not d.exec_(): @@ -1698,7 +1698,7 @@ def paste_isbn(self): def parse_clipboard_for_identifier(self): from calibre.ebooks.metadata.sources.prefs import msprefs from calibre.utils.formatter import EvalFormatter - text = unicode_type(QApplication.clipboard().text()).strip() + text = str(QApplication.clipboard().text()).strip() if not text: return False @@ -1768,7 +1768,7 @@ def __init__(self, parent, txt): self.resize(sz) def accept(self): - isbn = unicode_type(self.line_edit.text()) + isbn = str(self.line_edit.text()) if not check_isbn(isbn): return error_dialog(self, _('Invalid ISBN'), _('The ISBN you entered is not valid. Try again.'), @@ -1776,7 +1776,7 @@ def accept(self): QDialog.accept(self) def checkText(self, txt): - isbn = unicode_type(txt) + isbn = str(txt) if not isbn: sheet = '' extra = '' @@ -1790,7 +1790,7 @@ def checkText(self, txt): self.line_edit.setStyleSheet(sheet) def text(self): - return check_isbn(unicode_type(self.line_edit.text())) + return check_isbn(str(self.line_edit.text())) # }}} @@ -1816,7 +1816,7 @@ def __init__(self, parent): @property def current_val(self): - return clean_text(unicode_type(self.currentText())) + return clean_text(str(self.currentText())) @current_val.setter def current_val(self, val): diff --git a/src/calibre/gui2/metadata/config.py b/src/calibre/gui2/metadata/config.py index 7e4cf35932..20f6b05d79 100644 --- a/src/calibre/gui2/metadata/config.py +++ b/src/calibre/gui2/metadata/config.py @@ -15,7 +15,7 @@ from calibre.gui2.preferences.metadata_sources import FieldsModel as FM from calibre.utils.icu import sort_key -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class FieldsModel(FM): # {{{ @@ -134,10 +134,10 @@ def commit(self): if isinstance(w, (QSpinBox, QDoubleSpinBox)): val = w.value() elif isinstance(w, QLineEdit): - val = unicode_type(w.text()) + val = str(w.text()) elif isinstance(w, QCheckBox): val = w.isChecked() elif isinstance(w, QComboBox): idx = w.currentIndex() - val = unicode_type(w.itemData(idx) or '') + val = str(w.itemData(idx) or '') self.plugin.prefs[w.opt.name] = val diff --git a/src/calibre/gui2/metadata/diff.py b/src/calibre/gui2/metadata/diff.py index bd70e84fb6..86b8ddf03b 100644 --- a/src/calibre/gui2/metadata/diff.py +++ b/src/calibre/gui2/metadata/diff.py @@ -27,7 +27,7 @@ from calibre.gui2.widgets2 import RightClickButton from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.date import UNDEFINED_DATE -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues Widgets = namedtuple('Widgets', 'new old label button') @@ -52,7 +52,7 @@ def __init__(self, field, is_new, parent, metadata, extra): @property def value(self): - val = unicode_type(self.text()).strip() + val = str(self.text()).strip() ism = self.metadata['is_multiple'] if ism: if not val: @@ -87,7 +87,7 @@ def to_mi(self, mi): @property def current_val(self): - return unicode_type(self.text()) + return str(self.text()) @current_val.setter def current_val(self, val): @@ -221,7 +221,7 @@ def from_mi(self, mi): self.setCursorPosition(0) def to_mi(self, mi): - val = unicode_type(self.text()).strip() + val = str(self.text()).strip() try: series_index = float(val.rpartition('[')[-1].rstrip(']').strip()) except: diff --git a/src/calibre/gui2/metadata/pdf_covers.py b/src/calibre/gui2/metadata/pdf_covers.py index 16d17e2782..8399fcf9d8 100644 --- a/src/calibre/gui2/metadata/pdf_covers.py +++ b/src/calibre/gui2/metadata/pdf_covers.py @@ -20,7 +20,6 @@ from calibre.gui2 import error_dialog, file_icon_provider from calibre.ptempfile import PersistentTemporaryDirectory from calibre.gui2.progress_indicator import WaitLayout -from polyglot.builtins import unicode_type class CoverDelegate(QStyledItemDelegate): @@ -84,9 +83,9 @@ def start_rendering(self): @property def cover_path(self): for item in self.covers.selectedItems(): - return unicode_type(item.data(Qt.ItemDataRole.UserRole) or '') + return str(item.data(Qt.ItemDataRole.UserRole) or '') if self.covers.count() > 0: - return unicode_type(self.covers.item(0).data(Qt.ItemDataRole.UserRole) or '') + return str(self.covers.item(0).data(Qt.ItemDataRole.UserRole) or '') def cleanup(self): try: @@ -95,7 +94,7 @@ def cleanup(self): pass def render(self): - self.current_tdir = os.path.join(self.tdir, unicode_type(self.first)) + self.current_tdir = os.path.join(self.tdir, str(self.first)) self.error = None try: os.mkdir(self.current_tdir) diff --git a/src/calibre/gui2/metadata/single.py b/src/calibre/gui2/metadata/single.py index 8d5da3ff47..b68377324d 100644 --- a/src/calibre/gui2/metadata/single.py +++ b/src/calibre/gui2/metadata/single.py @@ -34,7 +34,7 @@ from calibre.utils.config import tweaks from calibre.utils.date import local_tz from calibre.utils.localization import canonicalize_lang -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems BASE_TITLE = _('Edit metadata') fetched_fields = ('title', 'title_sort', 'authors', 'author_sort', 'series', @@ -317,7 +317,7 @@ def update_paste_identifiers_menu(self): def edit_prefix_list(self): prefixes, ok = QInputDialog.getMultiLineText( self, _('Edit prefixes'), _('Enter prefixes, one on a line. The first prefix becomes the default.'), - '\n'.join(list(map(unicode_type, gprefs['paste_isbn_prefixes'])))) + '\n'.join(list(map(str, gprefs['paste_isbn_prefixes'])))) if ok: gprefs['paste_isbn_prefixes'] = list(filter(None, (x.strip() for x in prefixes.splitlines()))) or gprefs.defaults['paste_isbn_prefixes'] self.update_paste_identifiers_menu() diff --git a/src/calibre/gui2/metadata/single_download.py b/src/calibre/gui2/metadata/single_download.py index 30a9b2aa4d..7550b26700 100644 --- a/src/calibre/gui2/metadata/single_download.py +++ b/src/calibre/gui2/metadata/single_download.py @@ -37,7 +37,7 @@ from calibre import force_unicode from calibre.utils.ipc.simple_worker import fork_job, WorkerError from calibre.ptempfile import TemporaryDirectory -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot.queue import Queue, Empty # }}} @@ -144,7 +144,7 @@ def headerData(self, section, orientation, role): def data_as_text(self, book, col): if col == 0: - return unicode_type(book.gui_rank+1) + return str(book.gui_rank+1) if col == 1: t = book.title if book.title else _('Unknown') a = authors_to_string(book.authors) if book.authors else '' @@ -341,7 +341,7 @@ def color_to_string(col): if col.isValid(): col = col.toRgb() if col.isValid(): - ans = unicode_type(col.name()) + ans = str(col.name()) return ans c = color_to_string(QApplication.palette().color(QPalette.ColorGroup.Normal, @@ -492,7 +492,7 @@ def start(self, title=None, authors=None, identifiers={}): if 'isbn' in identifiers: simple_desc += 'ISBN: %s' % identifiers['isbn'] self.query.setText(simple_desc) - self.log(unicode_type(self.query.text())) + self.log(str(self.query.text())) self.worker = IdentifyWorker(self.log, self.abort, title, authors, identifiers, self.caches) @@ -831,7 +831,7 @@ def show_cover(self): pmap = self.model().cc if pmap is not None: from calibre.gui2.image_popup import ImageView - d = ImageView(self, pmap, unicode_type(idx.data(Qt.ItemDataRole.DisplayRole) or ''), geom_name='metadata_download_cover_popup_geom') + d = ImageView(self, pmap, str(idx.data(Qt.ItemDataRole.DisplayRole) or ''), geom_name='metadata_download_cover_popup_geom') d(use_exec=True) def copy_cover(self): diff --git a/src/calibre/gui2/notify.py b/src/calibre/gui2/notify.py index 85c5bcf760..17e11a19e2 100644 --- a/src/calibre/gui2/notify.py +++ b/src/calibre/gui2/notify.py @@ -12,7 +12,6 @@ from functools import lru_cache from calibre.constants import DEBUG, __appname__, get_osx_version, islinux, ismacos -from polyglot.builtins import unicode_type class Notifier: @@ -164,7 +163,7 @@ def __call__(self, body, summary=None, replaces_id=None, timeout=0): try: hide = False try: - if not isinstance(body, unicode_type): + if not isinstance(body, str): body = body.decode('utf-8') if ismacos and not self.systray.isVisible(): self.systray.show() diff --git a/src/calibre/gui2/open_with.py b/src/calibre/gui2/open_with.py index 2b010197b6..eb026d00e3 100644 --- a/src/calibre/gui2/open_with.py +++ b/src/calibre/gui2/open_with.py @@ -26,7 +26,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 polyglot.builtins import iteritems, string_or_bytes, unicode_type +from polyglot.builtins import iteritems, string_or_bytes ENTRY_ROLE = Qt.ItemDataRole.UserRole @@ -362,7 +362,7 @@ def choose_program(file_type='jpeg', parent=None, prefs=oprefs): entry = choose_manually(file_type, parent) if d.select_manually else d.selected_entry if entry is not None: entry = finalize_entry(entry) - entry['uuid'] = unicode_type(uuid.uuid4()) + entry['uuid'] = str(uuid.uuid4()) entries = oprefs['entries'] if oft not in entries: entries[oft] = [] diff --git a/src/calibre/gui2/preferences/__init__.py b/src/calibre/gui2/preferences/__init__.py index f9005d30a0..2e77dbd2ae 100644 --- a/src/calibre/gui2/preferences/__init__.py +++ b/src/calibre/gui2/preferences/__init__.py @@ -16,7 +16,7 @@ from calibre.utils.config import ConfigProxy from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.widgets import HistoryLineEdit -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes class AbortCommit(Exception): @@ -128,15 +128,15 @@ def __init__(self, name, config_obj, widget, gui_name=None, raise ValueError('Unknown data type %s' % self.gui_obj.__class__) if isinstance(self.config_obj, ConfigProxy) and \ - not unicode_type(self.gui_obj.toolTip()): + not str(self.gui_obj.toolTip()): h = self.config_obj.help(self.name) if h: self.gui_obj.setToolTip(h) - tt = unicode_type(self.gui_obj.toolTip()) + tt = str(self.gui_obj.toolTip()) if tt: - if not unicode_type(self.gui_obj.whatsThis()): + if not str(self.gui_obj.whatsThis()): self.gui_obj.setWhatsThis(tt) - if not unicode_type(self.gui_obj.statusTip()): + if not str(self.gui_obj.statusTip()): self.gui_obj.setStatusTip(tt) tt = '\n'.join(textwrap.wrap(tt, 70)) self.gui_obj.setToolTip(tt) @@ -204,17 +204,17 @@ def get_gui_val(self): elif self.datatype == 'number': val = self.gui_obj.value() elif self.datatype == 'string': - val = unicode_type(self.gui_obj.text()).strip() + val = str(self.gui_obj.text()).strip() if self.empty_string_is_None and not val: val = None elif self.datatype == 'choice': if isinstance(self.gui_obj, EditWithComplete): - val = unicode_type(self.gui_obj.text()) + val = str(self.gui_obj.text()) else: idx = self.gui_obj.currentIndex() if idx < 0: idx = 0 - val = unicode_type(self.gui_obj.itemData(idx) or '') + val = str(self.gui_obj.itemData(idx) or '') return val @@ -227,7 +227,7 @@ def set_gui_val(self, val): self.gui_obj.setText(x) def get_gui_val(self): - val = unicode_type(self.gui_obj.text()).strip() + val = str(self.gui_obj.text()).strip() ans = [] if val: ans = [x.strip() for x in val.split(',')] diff --git a/src/calibre/gui2/preferences/adding.py b/src/calibre/gui2/preferences/adding.py index 9d7b0e8253..c970630a73 100644 --- a/src/calibre/gui2/preferences/adding.py +++ b/src/calibre/gui2/preferences/adding.py @@ -17,7 +17,6 @@ from calibre.gui2.widgets import FilenamePattern from calibre.gui2.auto_add import AUTO_ADDED from calibre.gui2 import gprefs, choose_dir, error_dialog, question_dialog -from polyglot.builtins import unicode_type class ConfigWidget(ConfigWidgetBase, Ui_Form): @@ -134,7 +133,7 @@ def current_blocked_auto_formats(self): viewer = self.opt_blocked_auto_formats for i in range(viewer.count()): if viewer.item(i).checkState() == Qt.CheckState.Checked: - fmts.append(unicode_type(viewer.item(i).text())) + fmts.append(str(viewer.item(i).text())) return fmts # }}} @@ -147,7 +146,7 @@ def restore_defaults(self): self.add_filter_rules = [] def commit(self): - path = unicode_type(self.opt_auto_add_path.text()).strip() + path = str(self.opt_auto_add_path.text()).strip() if path != gprefs['auto_add_path']: if path: path = os.path.abspath(path) diff --git a/src/calibre/gui2/preferences/behavior.py b/src/calibre/gui2/preferences/behavior.py index 98b3a5c1d7..2c3caf0d4c 100644 --- a/src/calibre/gui2/preferences/behavior.py +++ b/src/calibre/gui2/preferences/behavior.py @@ -21,7 +21,6 @@ from calibre.ebooks.oeb.iterator import is_supported from calibre.constants import iswindows from calibre.utils.icu import sort_key -from polyglot.builtins import unicode_type def input_order_drop_event(self, ev): @@ -95,7 +94,7 @@ def restore_defaults(self): def commit(self): input_map = prefs['input_format_order'] - input_cols = [unicode_type(self.opt_input_order.item(i).data(Qt.ItemDataRole.UserRole) or '') for + input_cols = [str(self.opt_input_order.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.opt_input_order.count())] if input_map != input_cols: prefs['input_format_order'] = input_cols @@ -143,7 +142,7 @@ def current_internally_viewed_formats(self): viewer = self.opt_internally_viewed_formats for i in range(viewer.count()): if viewer.item(i).checkState() == Qt.CheckState.Checked: - fmts.append(unicode_type(viewer.item(i).text())) + fmts.append(str(viewer.item(i).text())) return fmts # }}} diff --git a/src/calibre/gui2/preferences/coloring.py b/src/calibre/gui2/preferences/coloring.py index 11905ae8c2..ea557dcb51 100644 --- a/src/calibre/gui2/preferences/coloring.py +++ b/src/calibre/gui2/preferences/coloring.py @@ -34,7 +34,7 @@ ) from calibre.utils.icu import lower, sort_key from calibre.utils.localization import lang_map -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems all_columns_string = _('All columns') @@ -172,12 +172,12 @@ def __init__(self, fm, parent=None): @property def current_col(self): idx = self.column_box.currentIndex() - return unicode_type(self.column_box.itemData(idx) or '') + return str(self.column_box.itemData(idx) or '') @current_col.setter def current_col(self, val): for idx in range(self.column_box.count()): - c = unicode_type(self.column_box.itemData(idx) or '') + c = str(self.column_box.itemData(idx) or '') if c == val: self.column_box.setCurrentIndex(idx) return @@ -186,12 +186,12 @@ def current_col(self, val): @property def current_action(self): idx = self.action_box.currentIndex() - return unicode_type(self.action_box.itemData(idx) or '') + return str(self.action_box.itemData(idx) or '') @current_action.setter def current_action(self, val): for idx in range(self.action_box.count()): - c = unicode_type(self.action_box.itemData(idx) or '') + c = str(self.action_box.itemData(idx) or '') if c == val: self.action_box.setCurrentIndex(idx) return @@ -199,7 +199,7 @@ def current_action(self, val): @property def current_val(self): - ans = unicode_type(self.value_box.text()).strip() + ans = str(self.value_box.text()).strip() if self.current_col == 'languages': rmap = {lower(v):k for k, v in iteritems(lang_map())} ans = rmap.get(lower(ans), ans) @@ -528,8 +528,8 @@ def update_filename_box(self): def update_color_label(self): pal = QApplication.palette() - bg1 = unicode_type(pal.color(QPalette.ColorRole.Base).name()) - bg2 = unicode_type(pal.color(QPalette.ColorRole.AlternateBase).name()) + bg1 = str(pal.color(QPalette.ColorRole.Base).name()) + bg2 = str(pal.color(QPalette.ColorRole.AlternateBase).name()) c = self.color_box.color self.color_label.setText('''  {st}  @@ -585,10 +585,10 @@ def get_filenames_from_box(self): for i in range(1, model.rowCount()): item = model.item(i, 0) if item.checkState() == Qt.CheckState.Checked: - fnames.append(lower(unicode_type(item.text()))) + fnames.append(lower(str(item.text()))) fname = ' : '.join(fnames) else: - fname = lower(unicode_type(self.filename_box.currentText())) + fname = lower(str(self.filename_box.currentText())) return fname def update_icon_filenames_in_box(self): @@ -647,7 +647,7 @@ def apply_rule(self, kind, col, rule): self.update_icon_filenames_in_box() for i in range(self.column_box.count()): - c = unicode_type(self.column_box.itemData(i) or '') + c = str(self.column_box.itemData(i) or '') if col == c: self.column_box.setCurrentIndex(i) break @@ -701,13 +701,13 @@ def rule(self): else: r.color = self.color_box.color idx = self.column_box.currentIndex() - col = unicode_type(self.column_box.itemData(idx) or '') + col = str(self.column_box.itemData(idx) or '') for c in self.conditions: condition = c.condition if condition is not None: r.add_condition(*condition) if self.rule_kind == 'icon': - kind = unicode_type(self.kind_box.itemData( + kind = str(self.kind_box.itemData( self.kind_box.currentIndex()) or '') else: kind = self.rule_kind diff --git a/src/calibre/gui2/preferences/columns.py b/src/calibre/gui2/preferences/columns.py index f2ddf7f663..4f8f513ded 100644 --- a/src/calibre/gui2/preferences/columns.py +++ b/src/calibre/gui2/preferences/columns.py @@ -15,7 +15,6 @@ from calibre.gui2.preferences.columns_ui import Ui_Form from calibre.gui2.preferences.create_custom_column import CreateCustomColumn from calibre.gui2 import error_dialog, question_dialog, ALL_COLUMNS -from polyglot.builtins import unicode_type class ConfigWidget(ConfigWidgetBase, Ui_Form): @@ -194,7 +193,7 @@ def del_custcol(self): if idx < 0: return error_dialog(self, '', _('You must select a column to delete it'), show=True) - col = unicode_type(self.opt_columns.item(idx, 0).data(Qt.ItemDataRole.UserRole) or '') + col = str(self.opt_columns.item(idx, 0).data(Qt.ItemDataRole.UserRole) or '') if col not in self.custcols: return error_dialog(self, '', _('The selected column is not a custom column'), show=True) @@ -223,7 +222,7 @@ def edit_custcol(self): model = self.gui.library_view.model() row = self.opt_columns.currentRow() try: - key = unicode_type(self.opt_columns.item(row, 0).data(Qt.ItemDataRole.UserRole)) + key = str(self.opt_columns.item(row, 0).data(Qt.ItemDataRole.UserRole)) except: key = '' CreateCustomColumn(self, row, key, model.orig_headers, ALL_COLUMNS) @@ -236,12 +235,12 @@ def edit_custcol(self): def apply_custom_column_changes(self): model = self.gui.library_view.model() db = model.db - config_cols = [unicode_type(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '') + config_cols = [str(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.opt_columns.rowCount())] if not config_cols: config_cols = ['title'] removed_cols = set(model.column_map) - set(config_cols) - hidden_cols = {unicode_type(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '') + hidden_cols = {str(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.opt_columns.rowCount()) if self.opt_columns.item(i, 0).checkState()==Qt.CheckState.Unchecked} hidden_cols = hidden_cols.union(removed_cols) # Hide removed cols diff --git a/src/calibre/gui2/preferences/conversion.py b/src/calibre/gui2/preferences/conversion.py index 10274cc4b7..3cb74cf380 100644 --- a/src/calibre/gui2/preferences/conversion.py +++ b/src/calibre/gui2/preferences/conversion.py @@ -23,7 +23,6 @@ from calibre.gui2.convert.toc import TOCWidget from calibre.customize.ui import input_format_plugins, output_format_plugins from calibre.gui2.convert import config_widget_for_input_plugin -from polyglot.builtins import unicode_type class Model(QStringListModel): @@ -93,7 +92,7 @@ def hfunc(name): if rec.option == name: ans = getattr(rec, 'help', None) if ans is not None: - return ans.replace('%default', unicode_type(rec.recommended_value)) + return ans.replace('%default', str(rec.recommended_value)) return cls(self, self.plumber.get_option_by_name, hfunc, None, None) self.load_conversion_widgets() diff --git a/src/calibre/gui2/preferences/create_custom_column.py b/src/calibre/gui2/preferences/create_custom_column.py index b635604286..cb30a17544 100644 --- a/src/calibre/gui2/preferences/create_custom_column.py +++ b/src/calibre/gui2/preferences/create_custom_column.py @@ -19,7 +19,7 @@ from calibre.gui2 import error_dialog from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor from calibre.utils.date import parse_date, UNDEFINED_DATE -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class CreateCustomColumn(QDialog): @@ -185,11 +185,11 @@ def __init__(self, parent, current_row, current_key, standard_colheads, standard self.default_value.setText(_('Now') if dv == 'now' else dv) elif ct == 'rating': if self.allow_half_stars.isChecked(): - self.default_value.setText(unicode_type(dv/2)) + self.default_value.setText(str(dv/2)) else: - self.default_value.setText(unicode_type(dv//2)) + self.default_value.setText(str(dv//2)) elif ct in ('int', 'float'): - self.default_value.setText(unicode_type(dv)) + self.default_value.setText(str(dv)) elif ct not in ('composite', '*composite'): self.default_value.setText(dv) @@ -200,12 +200,12 @@ def __init__(self, parent, current_row, current_key, standard_colheads, standard self.is_names.setChecked(c['display'].get('is_names', False)) self.description_box.setText(c['display'].get('description', '')) - all_colors = [unicode_type(s) for s in list(QColor.colorNames())] + all_colors = [str(s) for s in list(QColor.colorNames())] self.enum_colors_label.setToolTip('

    ' + ', '.join(all_colors) + '

    ') self.exec_() def shortcut_activated(self, url): # {{{ - which = unicode_type(url).split(':')[-1] + which = str(url).split(':')[-1] self.column_type_box.setCurrentIndex({ 'yesno': self.column_types_map['bool'], 'tags' : self.column_types_map['*text'], @@ -489,7 +489,7 @@ def datatype_changed(self, *args): self.allow_half_stars.setVisible(col_type == 'rating') def accept(self): - col = unicode_type(self.column_name_box.text()).strip() + col = str(self.column_name_box.text()).strip() if not col: return self.simple_error('', _('No lookup name was provided')) if col.startswith('#'): @@ -500,7 +500,7 @@ def accept(self): if col.endswith('_index'): return self.simple_error('', _('Lookup names cannot end with _index, ' 'because these names are reserved for the index of a series column.')) - col_heading = unicode_type(self.column_heading_box.text()).strip() + col_heading = str(self.column_heading_box.text()).strip() coldef = self.column_types[self.column_type_box.currentIndex()] col_type = coldef['datatype'] if col_type[0] == '*': @@ -535,12 +535,12 @@ def accept(self): display_dict = {} - default_val = (unicode_type(self.default_value.text()).strip() + default_val = (str(self.default_value.text()).strip() if col_type != 'composite' else None) if col_type == 'datetime': - if unicode_type(self.format_box.text()).strip(): - display_dict = {'date_format':unicode_type(self.format_box.text()).strip()} + if str(self.format_box.text()).strip(): + display_dict = {'date_format':str(self.format_box.text()).strip()} else: display_dict = {'date_format': None} if default_val: @@ -556,28 +556,28 @@ def accept(self): _('The default value must be "Now" or a date')) display_dict['default_value'] = default_val elif col_type == 'composite': - if not unicode_type(self.composite_box.text()).strip(): + if not str(self.composite_box.text()).strip(): return self.simple_error('', _('You must enter a template for ' 'composite columns')) - display_dict = {'composite_template':unicode_type(self.composite_box.text()).strip(), + display_dict = {'composite_template':str(self.composite_box.text()).strip(), 'composite_sort': ['text', 'number', 'date', 'bool'] [self.composite_sort_by.currentIndex()], 'make_category': self.composite_make_category.isChecked(), 'contains_html': self.composite_contains_html.isChecked(), } elif col_type == 'enumeration': - if not unicode_type(self.enum_box.text()).strip(): + if not str(self.enum_box.text()).strip(): return self.simple_error('', _('You must enter at least one ' 'value for enumeration columns')) - l = [v.strip() for v in unicode_type(self.enum_box.text()).split(',') if v.strip()] + l = [v.strip() for v in str(self.enum_box.text()).split(',') if v.strip()] l_lower = [v.lower() for v in l] for i,v in enumerate(l_lower): if v in l_lower[i+1:]: return self.simple_error('', _('The value "{0}" is in the ' 'list more than once, perhaps with different case').format(l[i])) - c = unicode_type(self.enum_colors.text()) + c = str(self.enum_colors.text()) if c: - c = [v.strip() for v in unicode_type(self.enum_colors.text()).split(',')] + c = [v.strip() for v in str(self.enum_colors.text()).split(',')] else: c = [] if len(c) != 0 and len(c) != len(l): @@ -595,8 +595,8 @@ def accept(self): elif col_type == 'text' and is_multiple: display_dict = {'is_names': self.is_names.isChecked()} elif col_type in ['int', 'float']: - if unicode_type(self.format_box.text()).strip(): - display_dict = {'number_format':unicode_type(self.format_box.text()).strip()} + if str(self.format_box.text()).strip(): + display_dict = {'number_format':str(self.format_box.text()).strip()} else: display_dict = {'number_format': None} if default_val: @@ -612,8 +612,8 @@ def accept(self): except: return self.simple_error(_('Invalid default value'), msg) elif col_type == 'comments': - display_dict['heading_position'] = unicode_type(self.comments_heading_position.currentData()) - display_dict['interpret_as'] = unicode_type(self.comments_type.currentData()) + display_dict['heading_position'] = str(self.comments_heading_position.currentData()) + display_dict['interpret_as'] = str(self.comments_type.currentData()) elif col_type == 'rating': half_stars = bool(self.allow_half_stars.isChecked()) display_dict['allow_half_stars'] = half_stars diff --git a/src/calibre/gui2/preferences/emailp.py b/src/calibre/gui2/preferences/emailp.py index 7bf851dd20..977bda5d10 100644 --- a/src/calibre/gui2/preferences/emailp.py +++ b/src/calibre/gui2/preferences/emailp.py @@ -14,7 +14,7 @@ from calibre.utils.config import ConfigProxy from calibre.utils.icu import numeric_sort_key from calibre.utils.smtp import config as smtp_prefs -from polyglot.builtins import unicode_type, as_unicode +from polyglot.builtins import as_unicode class EmailAccounts(QAbstractTableModel): # {{{ @@ -177,7 +177,7 @@ def add(self): c = 0 while y in self.accounts: c += 1 - y = x + unicode_type(c) + y = x + str(c) auto_send = len(self.accounts) < 1 self.beginResetModel() self.accounts[y] = ['MOBI, EPUB', auto_send, diff --git a/src/calibre/gui2/preferences/history.py b/src/calibre/gui2/preferences/history.py index 5d677fe0e1..8d38dd0f88 100644 --- a/src/calibre/gui2/preferences/history.py +++ b/src/calibre/gui2/preferences/history.py @@ -11,7 +11,6 @@ from qt.core import QComboBox, Qt from calibre.gui2 import config as gui_conf -from polyglot.builtins import unicode_type class HistoryBox(QComboBox): @@ -38,11 +37,11 @@ def set_value(self, val): self.setCurrentIndex(self.findText(val, Qt.MatchFlag.MatchFixedString)) def save_history(self, opt_name): - history = [unicode_type(self.itemText(i)) for i in range(self.count())] + history = [str(self.itemText(i)) for i in range(self.count())] ct = self.text() if ct not in history: history = [ct] + history gui_conf[opt_name] = history[:10] def text(self): - return unicode_type(self.currentText()).strip() + return str(self.currentText()).strip() diff --git a/src/calibre/gui2/preferences/look_feel.py b/src/calibre/gui2/preferences/look_feel.py index 51f803b337..4f1ef44478 100644 --- a/src/calibre/gui2/preferences/look_feel.py +++ b/src/calibre/gui2/preferences/look_feel.py @@ -38,7 +38,7 @@ from calibre.gui2.widgets2 import Dialog from calibre.gui2.actions.show_quickview import get_quickview_action_plugin from calibre.utils.resources import set_data -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class BusyCursor: @@ -555,7 +555,7 @@ def get_esc_lang(l): self.tabWidget.setCurrentIndex(0) keys = [QKeySequence('F11', QKeySequence.SequenceFormat.PortableText), QKeySequence( 'Ctrl+Shift+F', QKeySequence.SequenceFormat.PortableText)] - keys = [unicode_type(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in keys] + keys = [str(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in keys] self.fs_help_msg.setText(self.fs_help_msg.text()%( QKeySequence(QKeySequence.StandardKey.FullScreen).toString(QKeySequence.SequenceFormat.NativeText))) self.size_calculated.connect(self.update_cg_cache_size, type=Qt.ConnectionType.QueuedConnection) @@ -751,7 +751,7 @@ def build_font_obj(self): def update_font_display(self): font = self.build_font_obj() fi = QFontInfo(font) - name = unicode_type(fi.family()) + name = str(fi.family()) self.font_display.setFont(font) self.font_display.setText(name + ' [%dpt]'%fi.pointSize()) @@ -761,7 +761,7 @@ def change_font(self, *args): if fd.exec_() == QDialog.DialogCode.Accepted: font = fd.selectedFont() fi = QFontInfo(font) - self.current_font = [unicode_type(fi.family()), fi.pointSize(), + self.current_font = [str(fi.family()), fi.pointSize(), fi.weight(), fi.italic(), font.stretch()] self.update_font_display() self.changed_signal.emit() diff --git a/src/calibre/gui2/preferences/main.py b/src/calibre/gui2/preferences/main.py index 10a2b5b295..e116f0f51e 100644 --- a/src/calibre/gui2/preferences/main.py +++ b/src/calibre/gui2/preferences/main.py @@ -26,7 +26,6 @@ from calibre.gui2.preferences import ( AbortCommit, AbortInitialize, get_plugin, init_gui ) -from polyglot.builtins import unicode_type ICON_SIZE = 32 @@ -301,8 +300,8 @@ def process_child(child): if isinstance(g, QLabel): buddy = g.buddy() if buddy is not None and hasattr(buddy, 'toolTip'): - htext = unicode_type(buddy.toolTip()).strip() - etext = unicode_type(g.toolTip()).strip() + htext = str(buddy.toolTip()).strip() + etext = str(g.toolTip()).strip() if htext and not etext: g.setToolTip(htext) g.setWhatsThis(htext) diff --git a/src/calibre/gui2/preferences/plugboard.py b/src/calibre/gui2/preferences/plugboard.py index ce7e95e26f..88f0b7a1e2 100644 --- a/src/calibre/gui2/preferences/plugboard.py +++ b/src/calibre/gui2/preferences/plugboard.py @@ -24,7 +24,7 @@ from calibre.srv.content import plugboard_content_server_value, plugboard_content_server_formats from calibre.gui2.email import plugboard_email_value, plugboard_email_formats from calibre.utils.formatter import validation_formatter -from polyglot.builtins import native_string_type, unicode_type +from polyglot.builtins import native_string_type class ConfigWidget(ConfigWidgetBase, Ui_Form): @@ -143,7 +143,7 @@ def edit_device_changed(self, txt): self.clear_fields(new_boxes=False) return self.clear_fields(new_boxes=True) - self.current_device = unicode_type(txt) + self.current_device = str(txt) fpb = self.current_plugboards.get(self.current_format, None) if fpb is None: print('edit_device_changed: none format!') @@ -166,7 +166,7 @@ def edit_format_changed(self, txt): self.clear_fields(new_boxes=False) return self.clear_fields(new_boxes=True) - txt = unicode_type(txt) + txt = str(txt) fpb = self.current_plugboards.get(txt, None) if fpb is None: print('edit_format_changed: none editable format!') @@ -198,7 +198,7 @@ def new_device_changed(self, txt): self.clear_fields(edit_boxes=False) return self.clear_fields(edit_boxes=True) - self.current_device = unicode_type(txt) + self.current_device = str(txt) if self.current_format in self.current_plugboards and \ self.current_device in self.current_plugboards[self.current_format]: @@ -282,7 +282,7 @@ def new_format_changed(self, txt): self.new_device.setCurrentIndex(0) if txt: self.clear_fields(edit_boxes=True) - self.current_format = unicode_type(txt) + self.current_format = str(txt) self.check_if_writer_disabled(self.current_format) else: self.clear_fields(edit_boxes=False) @@ -291,7 +291,7 @@ def ok_clicked(self): pb = [] comments_in_dests = False for i in range(0, len(self.source_widgets)): - s = unicode_type(self.source_widgets[i].text()) + s = str(self.source_widgets[i].text()) if s: d = self.dest_widgets[i].currentIndex() if d != 0: @@ -300,7 +300,7 @@ def ok_clicked(self): except Exception as err: error_dialog(self, _('Invalid template'), '

    '+_('The template %s is invalid:')%s + - '
    '+unicode_type(err), show=True) + '
    '+str(err), show=True) return pb.append((s, self.dest_fields[d])) comments_in_dests = comments_in_dests or self.dest_fields[d] == 'comments' diff --git a/src/calibre/gui2/preferences/plugins.py b/src/calibre/gui2/preferences/plugins.py index 5827788f16..2c7cfbf90d 100644 --- a/src/calibre/gui2/preferences/plugins.py +++ b/src/calibre/gui2/preferences/plugins.py @@ -24,7 +24,7 @@ from calibre.utils.search_query_parser import SearchQueryParser from calibre.utils.icu import lower from calibre.constants import iswindows -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues class AdaptSQP(SearchQueryParser): @@ -204,7 +204,7 @@ def data(self, index, role): plugin = self.index_to_plugin(index) disabled = is_disabled(plugin) if role == Qt.ItemDataRole.DisplayRole: - ver = '.'.join(map(unicode_type, plugin.version)) + ver = '.'.join(map(str, plugin.version)) desc = '\n'.join(textwrap.wrap(plugin.description, 100)) ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc) c = plugin_customization(plugin) @@ -281,7 +281,7 @@ def find_next(self, *args): if not idx.isValid(): idx = self._plugin_model.index(0, 0) idx = self._plugin_model.find_next(idx, - unicode_type(self.search.currentText())) + str(self.search.currentText())) self.highlight_index(idx) def find_previous(self, *args): @@ -289,7 +289,7 @@ def find_previous(self, *args): if not idx.isValid(): idx = self._plugin_model.index(0, 0) idx = self._plugin_model.find_next(idx, - unicode_type(self.search.currentText()), backwards=True) + str(self.search.currentText()), backwards=True) self.highlight_index(idx) def toggle_plugin(self, *args): @@ -327,7 +327,7 @@ def add_plugin(self): plugin = add_plugin(path) except NameConflict as e: return error_dialog(self, _('Already exists'), - unicode_type(e), show=True) + str(e), show=True) self._plugin_model.beginResetModel() self._plugin_model.populate() self._plugin_model.endResetModel() @@ -349,7 +349,7 @@ def modify_plugin(self, op=''): index = self.plugin_view.currentIndex() if index.isValid(): if not index.parent().isValid(): - name = unicode_type(index.data() or '') + name = str(index.data() or '') return error_dialog(self, _('Error'), '

    '+ _('Select an actual plugin under %s to customize')%name, show=True, show_copy_button=False) diff --git a/src/calibre/gui2/preferences/save_template.py b/src/calibre/gui2/preferences/save_template.py index 09f116804b..d83e95c889 100644 --- a/src/calibre/gui2/preferences/save_template.py +++ b/src/calibre/gui2/preferences/save_template.py @@ -13,7 +13,6 @@ from calibre.library.save_to_disk import FORMAT_ARG_DESCS, preprocess_template from calibre.utils.formatter import validation_formatter from calibre.gui2.dialogs.template_dialog import TemplateDialog -from polyglot.builtins import unicode_type class SaveTemplate(QWidget, Ui_Form): @@ -75,7 +74,7 @@ def validate(self): except Exception as err: error_dialog(self, _('Invalid template'), '

    '+_('The template %s is invalid:')%tmpl + - '
    '+unicode_type(err), show=True) + '
    '+str(err), show=True) return False return True @@ -83,6 +82,6 @@ def set_value(self, val): self.opt_template.set_value(val) def save_settings(self, config, name): - val = unicode_type(self.opt_template.text()) + val = str(self.opt_template.text()) config.set(name, val) self.opt_template.save_history(self.option_name+'_template_history') diff --git a/src/calibre/gui2/preferences/search.py b/src/calibre/gui2/preferences/search.py index 71ce6ba422..1aa497a40f 100644 --- a/src/calibre/gui2/preferences/search.py +++ b/src/calibre/gui2/preferences/search.py @@ -16,7 +16,7 @@ from calibre.utils.config import prefs from calibre.utils.icu import sort_key from calibre.library.caches import set_use_primary_find_in_search -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class ConfigWidget(ConfigWidgetBase, Ui_Form): @@ -139,13 +139,13 @@ def muc_box_changed(self): def gst_save_clicked(self): idx = self.gst_names.currentIndex() - name = icu_lower(unicode_type(self.gst_names.currentText())) + name = icu_lower(str(self.gst_names.currentText())) if not name: return error_dialog(self.gui, _('Grouped search terms'), _('The search term cannot be blank'), show=True) if idx != 0: - orig_name = unicode_type(self.gst_names.itemData(idx) or '') + orig_name = str(self.gst_names.itemData(idx) or '') else: orig_name = '' if name != orig_name: @@ -159,7 +159,7 @@ def gst_save_clicked(self): _('That name is already used for User category'), show=True) - val = [v.strip() for v in unicode_type(self.gst_value.text()).split(',') if v.strip()] + val = [v.strip() for v in str(self.gst_value.text()).split(',') if v.strip()] if not val: return error_dialog(self.gui, _('Grouped search terms'), _('The value box cannot be empty'), show=True) @@ -176,7 +176,7 @@ def gst_delete_clicked(self): if self.gst_names.currentIndex() == 0: return error_dialog(self.gui, _('Grouped search terms'), _('The empty grouped search term cannot be deleted'), show=True) - name = unicode_type(self.gst_names.currentText()) + name = str(self.gst_names.currentText()) if name in self.gst: del self.gst[name] self.fill_gst_box(select='') @@ -211,7 +211,7 @@ def gst_index_changed(self, idx): if idx == 0: self.gst_value.setText('') else: - name = unicode_type(self.gst_names.itemData(idx) or '') + name = str(self.gst_names.itemData(idx) or '') self.gst_value.setText(','.join(self.gst[name])) self.gst_value.blockSignals(False) @@ -225,13 +225,13 @@ def commit(self): self.db.new_api.set_pref('grouped_search_terms', self.gst) self.db.field_metadata.add_grouped_search_terms(self.gst) self.db.new_api.set_pref('similar_authors_search_key', - unicode_type(self.similar_authors_search_key.currentText())) + str(self.similar_authors_search_key.currentText())) self.db.new_api.set_pref('similar_tags_search_key', - unicode_type(self.similar_tags_search_key.currentText())) + str(self.similar_tags_search_key.currentText())) self.db.new_api.set_pref('similar_series_search_key', - unicode_type(self.similar_series_search_key.currentText())) + str(self.similar_series_search_key.currentText())) self.db.new_api.set_pref('similar_publisher_search_key', - unicode_type(self.similar_publisher_search_key.currentText())) + str(self.similar_publisher_search_key.currentText())) return ConfigWidgetBase.commit(self) def refresh_gui(self, gui): diff --git a/src/calibre/gui2/preferences/server.py b/src/calibre/gui2/preferences/server.py index 208cbe0f43..898b5edb1b 100644 --- a/src/calibre/gui2/preferences/server.py +++ b/src/calibre/gui2/preferences/server.py @@ -35,7 +35,7 @@ ) from calibre.utils.icu import primary_sort_key from calibre.utils.shared_file import share_open -from polyglot.builtins import as_bytes, unicode_type +from polyglot.builtins import as_bytes if iswindows and not isportable: @@ -169,7 +169,7 @@ def get(self): return self.text().strip() or None def set(self, val): - self.setText(unicode_type(val or '')) + self.setText(str(val or '')) class Path(QWidget): @@ -199,7 +199,7 @@ def get(self): return self.text.text().strip() or None def set(self, val): - self.text.setText(unicode_type(val or '')) + self.text.setText(str(val or '')) def choose(self): ans = choose_files(self, 'choose_path_srv_opts_' + self.dname, _('Choose a file'), select_only_single_file=True) diff --git a/src/calibre/gui2/preferences/template_functions.py b/src/calibre/gui2/preferences/template_functions.py index 5bcaa1ef34..5513b44d5c 100644 --- a/src/calibre/gui2/preferences/template_functions.py +++ b/src/calibre/gui2/preferences/template_functions.py @@ -16,7 +16,7 @@ compile_user_function, compile_user_template_functions, formatter_functions, function_pref_is_python, function_pref_name, load_user_template_functions ) -from polyglot.builtins import iteritems, native_string_type, unicode_type +from polyglot.builtins import iteritems, native_string_type class ConfigWidget(ConfigWidgetBase, Ui_Form): @@ -245,7 +245,7 @@ def build_function_names_box(self, scroll_to=''): self.delete_button.setEnabled(True) def delete_button_clicked(self): - name = unicode_type(self.function_name.currentText()) + name = str(self.function_name.currentText()) if name in self.builtins: error_dialog(self.gui, _('Template functions'), _('You cannot delete a built-in function'), show=True) @@ -262,7 +262,7 @@ def delete_button_clicked(self): def create_button_clicked(self, use_name=None): self.changed_signal.emit() - name = use_name if use_name else unicode_type(self.function_name.currentText()) + name = use_name if use_name else str(self.function_name.currentText()) if name in self.funcs: error_dialog(self.gui, _('Template functions'), _('Name %s already used')%(name,), show=True) @@ -284,8 +284,8 @@ def create_button_clicked(self, use_name=None): if not box.exec_(): return try: - prog = unicode_type(self.program.toPlainText()) - cls = compile_user_function(name, unicode_type(self.documentation.toPlainText()), + prog = str(self.program.toPlainText()) + cls = compile_user_function(name, str(self.documentation.toPlainText()), self.argument_count.value(), prog) self.funcs[name] = cls self.build_function_names_box(scroll_to=name) @@ -302,7 +302,7 @@ def function_name_edited(self, txt): self.program.setReadOnly(False) def function_index_changed(self, txt): - txt = unicode_type(txt) + txt = str(txt) self.create_button.setEnabled(False) if not txt: self.argument_count.clear() @@ -331,7 +331,7 @@ def function_index_changed(self, txt): self.replace_button.setEnabled(False) def replace_button_clicked(self): - name = unicode_type(self.function_name.currentText()) + name = str(self.function_name.currentText()) self.delete_button_clicked() self.create_button_clicked(use_name=name) @@ -379,7 +379,7 @@ def st_build_function_names_box(self, scroll_to=''): self.te_name.setCurrentIndex(idx) def st_delete_button_clicked(self): - name = unicode_type(self.te_name.currentText()) + name = str(self.te_name.currentText()) if name in self.st_funcs: del self.st_funcs[name] self.changed_signal.emit() @@ -394,18 +394,18 @@ def st_delete_button_clicked(self): def st_create_button_clicked(self, use_name=None): self.changed_signal.emit() - name = use_name if use_name else unicode_type(self.te_name.currentText()) + name = use_name if use_name else str(self.te_name.currentText()) for k,v in formatter_functions().get_functions().items(): if k == name and v.is_python: error_dialog(self.gui, _('Stored templates'), _('The name {} is already used for template function').format(name), show=True) try: - prog = unicode_type(self.te_textbox.toPlainText()) + prog = str(self.te_textbox.toPlainText()) if not prog.startswith('program:'): error_dialog(self.gui, _('Stored templates'), _('The stored template must begin with "program:"'), show=True) - cls = compile_user_function(name, unicode_type(self.template_editor.new_doc.toPlainText()), + cls = compile_user_function(name, str(self.template_editor.new_doc.toPlainText()), 0, prog) self.st_funcs[name] = cls self.st_build_function_names_box(scroll_to=name) @@ -423,7 +423,7 @@ def st_template_name_edited(self, txt): self.te_textbox.setReadOnly(False) def st_function_index_changed(self, txt): - txt = unicode_type(txt) + txt = str(txt) if self.st_current_program_name: if self.st_current_program_text != self.te_textbox.toPlainText(): box = warning_dialog(self.gui, _('Template functions'), @@ -451,7 +451,7 @@ def st_function_index_changed(self, txt): self.st_template_name_edited(txt) def st_replace_button_clicked(self): - name = unicode_type(self.te_name.currentText()) + name = str(self.te_name.currentText()) self.st_current_program_text = self.te_textbox.toPlainText() self.st_delete_button_clicked() self.st_create_button_clicked(use_name=name) diff --git a/src/calibre/gui2/preferences/texture_chooser.py b/src/calibre/gui2/preferences/texture_chooser.py index 16feb1f770..f472daa233 100644 --- a/src/calibre/gui2/preferences/texture_chooser.py +++ b/src/calibre/gui2/preferences/texture_chooser.py @@ -14,7 +14,6 @@ from calibre.constants import config_dir from calibre.gui2 import choose_files, error_dialog from calibre.utils.icu import sort_key -from polyglot.builtins import unicode_type def texture_dir(): @@ -86,7 +85,7 @@ def __init__(self, parent=None, initial=None): self.update_remove_state() if initial: - existing = {unicode_type(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))} + existing = {str(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))} item = existing.get(initial, None) if item is not None: item.setSelected(True) @@ -117,7 +116,7 @@ def add_texture(self): path = path[0] fname = os.path.basename(path) name = fname.rpartition('.')[0] - existing = {unicode_type(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))} + existing = {str(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))} dest = os.path.join(self.tdir, fname) with open(path, 'rb') as s, open(dest, 'wb') as f: shutil.copyfileobj(s, f) @@ -136,7 +135,7 @@ def selected_item(self): @property def selected_fname(self): try: - return unicode_type(self.selected_item.data(Qt.ItemDataRole.UserRole) or '') + return str(self.selected_item.data(Qt.ItemDataRole.UserRole) or '') except (AttributeError, TypeError): pass @@ -146,7 +145,7 @@ def remove_texture(self): if self.selected_fname.startswith(':'): return error_dialog(self, _('Cannot remove'), _('Cannot remove builtin textures'), show=True) - os.remove(unicode_type(self.selected_item.data(Qt.ItemDataRole.UserRole+1) or '')) + os.remove(str(self.selected_item.data(Qt.ItemDataRole.UserRole+1) or '')) self.images.takeItem(self.images.row(self.selected_item)) diff --git a/src/calibre/gui2/preferences/toolbar.py b/src/calibre/gui2/preferences/toolbar.py index a2c4ea4830..4e70bda08d 100644 --- a/src/calibre/gui2/preferences/toolbar.py +++ b/src/calibre/gui2/preferences/toolbar.py @@ -13,7 +13,6 @@ from calibre.gui2 import gprefs, warning_dialog, error_dialog from calibre.gui2.preferences import ConfigWidgetBase, test_widget, AbortCommit from calibre.utils.icu import primary_sort_key -from polyglot.builtins import unicode_type def sort_key_for_action(ac): @@ -291,7 +290,7 @@ def current_entered(self, index): self.help_text.setText(tt) def what_changed(self, idx): - key = unicode_type(self.what.itemData(idx) or '') + key = str(self.what.itemData(idx) or '') if key == 'blank': self.actions_widget.setVisible(False) self.spacer_widget.setVisible(True) diff --git a/src/calibre/gui2/preferences/tweaks.py b/src/calibre/gui2/preferences/tweaks.py index 4a60a4abba..f3439b1b61 100644 --- a/src/calibre/gui2/preferences/tweaks.py +++ b/src/calibre/gui2/preferences/tweaks.py @@ -26,7 +26,7 @@ ) from calibre.utils.icu import lower from calibre.utils.search_query_parser import ParseException, SearchQueryParser -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems ROOT = QModelIndex() @@ -263,7 +263,7 @@ def to_string(self): ' edit it unless you know what you are doing.', '', ] for tweak in self.tweaks: - ans.extend(['', unicode_type(tweak), '']) + ans.extend(['', str(tweak), '']) if self.plugin_tweaks: ans.extend(['', '', @@ -495,7 +495,7 @@ def plugin_tweaks(self): if d.exec_() == QDialog.DialogCode.Accepted: g, l = {}, {} try: - exec(unicode_type(d.edit.toPlainText()), g, l) + exec(str(d.edit.toPlainText()), g, l) except: import traceback return error_dialog(self, _('Failed'), @@ -536,7 +536,7 @@ def apply_tweak(self): if idx.isValid(): l, g = {}, {} try: - exec(unicode_type(self.edit_tweak.toPlainText()), g, l) + exec(str(self.edit_tweak.toPlainText()), g, l) except: import traceback error_dialog(self.gui, _('Failed'), @@ -593,7 +593,7 @@ def find_next(self, *args): if not idx.isValid(): idx = self._model.index(0) idx = self._model.find_next(idx, - unicode_type(self.search.currentText())) + str(self.search.currentText())) self.highlight_index(idx) def find_previous(self, *args): @@ -601,7 +601,7 @@ def find_previous(self, *args): if not idx.isValid(): idx = self._model.index(0) idx = self._model.find_next(idx, - unicode_type(self.search.currentText()), backwards=True) + str(self.search.currentText()), backwards=True) self.highlight_index(idx) diff --git a/src/calibre/gui2/proceed.py b/src/calibre/gui2/proceed.py index dd7de9774c..6154b9315a 100644 --- a/src/calibre/gui2/proceed.py +++ b/src/calibre/gui2/proceed.py @@ -15,7 +15,6 @@ from calibre.constants import __version__ from calibre.gui2.dialogs.message_box import ViewLog -from polyglot.builtins import unicode_type Question = namedtuple('Question', 'payload callback cancel_callback ' 'title msg html_log log_viewer_title log_is_file det_msg ' @@ -171,9 +170,9 @@ def parent_resized(self): def copy_to_clipboard(self, *args): QApplication.clipboard().setText( 'calibre, version %s\n%s: %s\n\n%s' % - (__version__, unicode_type(self.windowTitle()), - unicode_type(self.msg_label.text()), - unicode_type(self.det_msg.toPlainText()))) + (__version__, str(self.windowTitle()), + str(self.msg_label.text()), + str(self.det_msg.toPlainText()))) self.copy_button.setText(_('Copied')) def action_clicked(self): @@ -211,7 +210,7 @@ def do_ask_question(self, callback, payload, checkbox_checked): self.show_question() def toggle_det_msg(self, *args): - vis = unicode_type(self.det_msg_toggle.text()) == self.hide_det_msg + vis = str(self.det_msg_toggle.text()) == self.hide_det_msg self.det_msg_toggle.setText(self.show_det_msg if vis else self.hide_det_msg) self.det_msg.setVisible(not vis) diff --git a/src/calibre/gui2/qt_file_dialogs.py b/src/calibre/gui2/qt_file_dialogs.py index dbd45da63a..1506111881 100644 --- a/src/calibre/gui2/qt_file_dialogs.py +++ b/src/calibre/gui2/qt_file_dialogs.py @@ -8,7 +8,7 @@ from qt.core import QFileDialog, QObject from calibre.gui2.linux_file_dialogs import dialog_name, image_extensions -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes from polyglot.urllib import unquote @@ -117,7 +117,7 @@ def __init__( ftext, "", opts) if fs and fs[0]: for f in fs[0]: - f = unicode_type(f) + f = str(f) if not f: continue if not os.path.exists(f): @@ -130,11 +130,11 @@ def __init__( if mode == QFileDialog.FileMode.Directory: opts |= QFileDialog.Option.ShowDirsOnly with adapt_menubar: - f = unicode_type(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) + f = str(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) if os.path.exists(f): self.selected_files.append(f) if self.selected_files: - self.selected_files = [unicode_type(q) for q in self.selected_files] + self.selected_files = [str(q) for q in self.selected_files] saved_loc = self.selected_files[0] if os.path.isfile(saved_loc): saved_loc = os.path.dirname(saved_loc) @@ -144,7 +144,7 @@ def __init__( def get_files(self): if self.selected_files is None: - return tuple(os.path.abspath(unicode_type(i)) for i in self.fd.selectedFiles()) + return tuple(os.path.abspath(str(i)) for i in self.fd.selectedFiles()) return tuple(self.selected_files) diff --git a/src/calibre/gui2/save.py b/src/calibre/gui2/save.py index 667724b7f5..33f2d0f1f1 100644 --- a/src/calibre/gui2/save.py +++ b/src/calibre/gui2/save.py @@ -22,7 +22,7 @@ from calibre.utils.formatter_functions import load_user_template_functions from calibre.utils.ipc.pool import Pool, Failure from calibre.library.save_to_disk import sanitize_args, get_path_components, find_plugboard, plugboard_save_to_disk_value -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot.queue import Empty BookId = namedtuple('BookId', 'title authors') @@ -267,7 +267,7 @@ def write_book(self, book_id, mi, components, fmts): except Failure as err: error_dialog(self.pd, _('Critical failure'), _( 'Could not save books to disk, click "Show details" for more information'), - det_msg=unicode_type(err.failure_message) + '\n' + unicode_type(err.details), show=True) + det_msg=str(err.failure_message) + '\n' + str(err.details), show=True) self.pd.canceled = True else: self.pd.value += 1 @@ -301,7 +301,7 @@ def do_one_update(self): except Failure as err: error_dialog(self.pd, _('Critical failure'), _( 'Could not save books to disk, click "Show details" for more information'), - det_msg=unicode_type(err.failure_message) + '\n' + unicode_type(err.details), show=True) + det_msg=str(err.failure_message) + '\n' + str(err.details), show=True) self.pd.canceled = True except RuntimeError: pass # tasks not completed diff --git a/src/calibre/gui2/search_box.py b/src/calibre/gui2/search_box.py index 3f94678bfd..88c7f7dd38 100644 --- a/src/calibre/gui2/search_box.py +++ b/src/calibre/gui2/search_box.py @@ -20,13 +20,13 @@ from calibre.gui2.dialogs.saved_search_editor import SavedSearchEditor from calibre.gui2.dialogs.search import SearchDialog from calibre.utils.icu import primary_sort_key -from polyglot.builtins import native_string_type, unicode_type, string_or_bytes +from polyglot.builtins import native_string_type, string_or_bytes -class AsYouType(unicode_type): +class AsYouType(str): def __new__(cls, text): - self = unicode_type.__new__(cls, text) + self = str.__new__(cls, text) self.as_you_type = True return self @@ -196,7 +196,7 @@ def search_done(self, ok): if isinstance(ok, string_or_bytes): self.setToolTip(ok) ok = False - if not unicode_type(self.currentText()).strip(): + if not str(self.currentText()).strip(): self.clear(emit_search=False) return self._in_a_search = ok @@ -219,7 +219,7 @@ def key_pressed(self, event): if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter): self.do_search() self.focus_to_library.emit() - elif self.as_you_type and unicode_type(event.text()): + elif self.as_you_type and str(event.text()): self.timer.start(1500) # Comes from the combobox itself @@ -251,7 +251,7 @@ def history_selected(self, text): def _do_search(self, store_in_history=True, as_you_type=False): self.hide_completer_popup() - text = unicode_type(self.currentText()).strip() + text = str(self.currentText()).strip() if not text: return self.clear() if as_you_type: @@ -269,7 +269,7 @@ def _do_search(self, store_in_history=True, as_you_type=False): self.insertItem(0, t) self.setCurrentIndex(0) self.block_signals(False) - history = [unicode_type(self.itemText(i)) for i in + history = [str(self.itemText(i)) for i in range(self.count())] config[self.opt_name] = history @@ -312,7 +312,7 @@ def in_a_search(self): @property def current_text(self): - return unicode_type(self.lineEdit().text()) + return str(self.lineEdit().text()) # }}} @@ -376,7 +376,7 @@ def key_pressed(self, event): def saved_search_selected(self, qname): from calibre.gui2.ui import get_gui db = get_gui().current_db - qname = unicode_type(qname) + qname = str(qname) if qname is None or not qname.strip(): self.search_box.clear() return @@ -403,9 +403,9 @@ def initialize_saved_search_names(self): def save_search_button_clicked(self): from calibre.gui2.ui import get_gui db = get_gui().current_db - name = unicode_type(self.currentText()) + name = str(self.currentText()) if not name.strip(): - name = unicode_type(self.search_box.text()).replace('"', '') + name = str(self.search_box.text()).replace('"', '') name = name.replace('\\', '') if not name: error_dialog(self, _('Create saved search'), @@ -417,7 +417,7 @@ def save_search_button_clicked(self): _('There is no search to save'), show=True) return db.saved_search_delete(name) - db.saved_search_add(name, unicode_type(self.search_box.text())) + db.saved_search_add(name, str(self.search_box.text())) # now go through an initialization cycle to ensure that the combobox has # the new search in it, that it is selected, and that the search box # references the new search instead of the text in the search. @@ -438,10 +438,10 @@ def delete_current_search(self): 'permanently deleted. Are you sure?') + '

    ', 'saved_search_delete', self): return - ss = db.saved_search_lookup(unicode_type(self.currentText())) + ss = db.saved_search_lookup(str(self.currentText())) if ss is None: return - db.saved_search_delete(unicode_type(self.currentText())) + db.saved_search_delete(str(self.currentText())) self.clear() self.search_box.clear() self.changed.emit() @@ -453,7 +453,7 @@ def copy_search_button_clicked(self): idx = self.currentIndex() if idx < 0: return - self.search_box.set_search_string(db.saved_search_lookup(unicode_type(self.currentText()))) + self.search_box.set_search_string(db.saved_search_lookup(str(self.currentText()))) # }}} @@ -477,7 +477,7 @@ def init_search_box_mixin(self): self.search.setMaximumWidth(self.width()-150) self.action_focus_search = QAction(self) shortcuts = list( - map(lambda x:unicode_type(x.toString(QKeySequence.SequenceFormat.PortableText)), + map(lambda x:str(x.toString(QKeySequence.SequenceFormat.PortableText)), QKeySequence.keyBindings(QKeySequence.StandardKey.Find))) shortcuts += ['/', 'Alt+S'] self.keyboard.register_shortcut('start search', _('Start search'), @@ -485,7 +485,7 @@ def init_search_box_mixin(self): self.action_focus_search.triggered.connect(self.focus_search_box) self.addAction(self.action_focus_search) self.search.setStatusTip(re.sub(r'<\w+>', ' ', - unicode_type(self.search.toolTip()))) + str(self.search.toolTip()))) self.set_highlight_only_button_icon() self.highlight_only_button.clicked.connect(self.highlight_only_clicked) tt = _('Enable or disable search highlighting.') + '

    ' diff --git a/src/calibre/gui2/search_restriction_mixin.py b/src/calibre/gui2/search_restriction_mixin.py index 5b3142c33d..0b72679efc 100644 --- a/src/calibre/gui2/search_restriction_mixin.py +++ b/src/calibre/gui2/search_restriction_mixin.py @@ -17,7 +17,6 @@ from calibre.utils.icu import sort_key from calibre.utils.search_query_parser import ParseException from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import unicode_type class SelectNames(QDialog): # {{{ @@ -51,7 +50,7 @@ def __init__(self, names, txt, parent=None): @property def names(self): for item in self._names.selectedItems(): - yield unicode_type(item.data(Qt.ItemDataRole.DisplayRole) or '') + yield str(item.data(Qt.ItemDataRole.DisplayRole) or '') @property def match_type(self): @@ -187,7 +186,7 @@ def __init__(self, gui, existing_names, editing=None): def search_text_changed(self, txt): db = self.gui.current_db searches = [_('Saved searches recognized in the expression:')] - txt = unicode_type(txt) + txt = str(txt) while txt: p = txt.partition('search:') if p[1]: # found 'search:' @@ -218,7 +217,7 @@ def search_text_changed(self, txt): self.saved_searches_label.setPlainText('\n'.join(searches)) def name_text_edited(self, new_name): - self.new_name = unicode_type(new_name) + self.new_name = str(new_name) def name_index_changed(self, dex): if self.editing and (self.vl_text.text() != self.original_search or @@ -234,12 +233,12 @@ def name_index_changed(self, dex): return self.new_name = self.editing = self.vl_name.currentText() self.original_index = dex - self.original_search = unicode_type(self.vl_name.itemData(dex) or '') + self.original_search = str(self.vl_name.itemData(dex) or '') self.vl_text.setText(self.original_search) def link_activated(self, url): db = self.gui.current_db - f, txt = unicode_type(url).partition('.')[0::2] + f, txt = str(url).partition('.')[0::2] if f == 'search': names = db.saved_search_names() else: @@ -259,7 +258,7 @@ def link_activated(self, url): self.vl_text.setCursorPosition(0) def accept(self): - n = unicode_type(self.vl_name.currentText()).strip() + n = str(self.vl_name.currentText()).strip() if not n: error_dialog(self.gui, _('No name'), _('You must provide a name for the new Virtual library'), @@ -279,7 +278,7 @@ def accept(self): default_yes=False): return - v = unicode_type(self.vl_text.text()).strip() + v = str(self.vl_text.text()).strip() if not v: error_dialog(self.gui, _('No search string'), _('You must provide a search to define the new Virtual library'), @@ -545,7 +544,7 @@ def build_search_restriction_list(self): current_restriction_text = None if self.search_restriction.count() > 1: - txt = unicode_type(self.search_restriction.itemText(2)) + txt = str(self.search_restriction.itemText(2)) if txt.startswith('*'): current_restriction_text = txt self.search_restriction.clear() @@ -593,14 +592,14 @@ def apply_named_search_restriction(self, name=None): def apply_text_search_restriction(self, search): if not self.search_restriction_list_built: self.build_search_restriction_list() - search = unicode_type(search) + search = str(search) if not search: self.search_restriction.setCurrentIndex(0) self._apply_search_restriction('', '') else: s = '*' + search if self.search_restriction.count() > 1: - txt = unicode_type(self.search_restriction.itemText(2)) + txt = str(self.search_restriction.itemText(2)) if txt.startswith('*'): self.search_restriction.setItemText(2, s) else: @@ -614,12 +613,12 @@ def apply_search_restriction(self, i): if not self.search_restriction_list_built: self.build_search_restriction_list() if i == 1: - self.apply_text_search_restriction(unicode_type(self.search.currentText())) - elif i == 2 and unicode_type(self.search_restriction.currentText()).startswith('*'): + self.apply_text_search_restriction(str(self.search.currentText())) + elif i == 2 and str(self.search_restriction.currentText()).startswith('*'): self.apply_text_search_restriction( - unicode_type(self.search_restriction.currentText())[1:]) + str(self.search_restriction.currentText())[1:]) else: - r = unicode_type(self.search_restriction.currentText()) + r = str(self.search_restriction.currentText()) if r is not None and r != '': restriction = 'search:"%s"'%(r) else: diff --git a/src/calibre/gui2/shortcuts.py b/src/calibre/gui2/shortcuts.py index 14f49d1045..2a61f14afd 100644 --- a/src/calibre/gui2/shortcuts.py +++ b/src/calibre/gui2/shortcuts.py @@ -17,7 +17,6 @@ from calibre.gui2 import error_dialog from calibre.utils.config import XMLConfig from calibre.utils.icu import sort_key -from polyglot.builtins import unicode_type DEFAULTS = Qt.ItemDataRole.UserRole DESCRIPTION = Qt.ItemDataRole.UserRole + 1 @@ -119,7 +118,7 @@ def key_press_event(self, ev, which=0): dup_desc = self.dup_check(sequence, self.key) if dup_desc is not None: error_dialog(self, _('Already assigned'), - unicode_type(sequence.toString(QKeySequence.SequenceFormat.NativeText)) + ' ' + + str(sequence.toString(QKeySequence.SequenceFormat.NativeText)) + ' ' + _('already assigned to') + ' ' + dup_desc, show=True) self.clear_clicked(which=which) @@ -170,12 +169,12 @@ def createEditor(self, parent, option, index): def setEditorData(self, editor, index): defs = index.data(DEFAULTS) - defs = _(' or ').join([unicode_type(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in defs]) - editor.key = unicode_type(index.data(KEY)) + defs = _(' or ').join([str(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in defs]) + editor.key = str(index.data(KEY)) editor.default_shortcuts.setText(_('&Default') + ': %s' % defs) editor.default_shortcuts.setChecked(True) editor.header.setText('%s: %s'%(_('Customize shortcuts for'), - unicode_type(index.data(DESCRIPTION)))) + str(index.data(DESCRIPTION)))) custom = index.data(CUSTOM) if custom: editor.custom.setChecked(True) @@ -251,7 +250,7 @@ def duplicate_check(self, seq, ignore): return self.descriptions[key] def get_shortcuts(self, key): - return [unicode_type(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in + return [str(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in self.get_sequences(key)] def data(self, index, role): @@ -280,7 +279,7 @@ def data(self, index, role): def set_data(self, index, custom): key = self.order[index.row()] if custom: - self.custom[key] = [unicode_type(x.toString(QKeySequence.SequenceFormat.PortableText)) for x in custom] + self.custom[key] = [str(x.toString(QKeySequence.SequenceFormat.PortableText)) for x in custom] elif key in self.custom: del self.custom[key] diff --git a/src/calibre/gui2/splash_screen.py b/src/calibre/gui2/splash_screen.py index 2487978135..1c17122710 100644 --- a/src/calibre/gui2/splash_screen.py +++ b/src/calibre/gui2/splash_screen.py @@ -10,7 +10,6 @@ from calibre.constants import __appname__, numeric_version from calibre.utils.monotonic import monotonic -from polyglot.builtins import unicode_type class SplashScreen(QSplashScreen): @@ -36,7 +35,7 @@ def __init__(self, develop=False): f.setPixelSize(self.total_height) f.setItalic(True), f.setBold(True) f = QFontMetrics(f) - self.num_ch = unicode_type(max(3, numeric_version[0])) + self.num_ch = str(max(3, numeric_version[0])) self.footer_font = f = QFont() f.setPointSize(self.FOOTER_SIZE) f.setItalic(True) diff --git a/src/calibre/gui2/store/basic_config.py b/src/calibre/gui2/store/basic_config.py index 3212f35f91..40390e69e4 100644 --- a/src/calibre/gui2/store/basic_config.py +++ b/src/calibre/gui2/store/basic_config.py @@ -8,7 +8,6 @@ from qt.core import QWidget from calibre.gui2.store.basic_config_widget_ui import Ui_Form -from polyglot.builtins import unicode_type class BasicStoreConfigWidget(QWidget, Ui_Form): @@ -38,5 +37,5 @@ def config_widget(self): def save_settings(self, config_widget): self.config['open_external'] = config_widget.open_external.isChecked() - tags = unicode_type(config_widget.tags.text()) + tags = str(config_widget.tags.text()) self.config['tags'] = tags diff --git a/src/calibre/gui2/store/config/chooser/adv_search_builder.py b/src/calibre/gui2/store/config/chooser/adv_search_builder.py index d40fd27c84..76de44a3ab 100644 --- a/src/calibre/gui2/store/config/chooser/adv_search_builder.py +++ b/src/calibre/gui2/store/config/chooser/adv_search_builder.py @@ -12,7 +12,6 @@ from calibre.gui2.store.config.chooser.adv_search_builder_ui import Ui_Dialog from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import unicode_type class AdvSearchBuilderDialog(QDialog, Ui_Dialog): @@ -77,7 +76,7 @@ def adv_search_string(self): self.mc = '=' else: self.mc = '~' - all, any, phrase, none = map(lambda x: unicode_type(x.text()), + all, any, phrase, none = map(lambda x: str(x.text()), (self.all, self.any, self.phrase, self.none)) all, any, none = map(self.tokens, (all, any, none)) phrase = phrase.strip() @@ -96,11 +95,11 @@ def adv_search_string(self): return ans def token(self): - txt = unicode_type(self.text.text()).strip() + txt = str(self.text.text()).strip() if txt: if self.negate.isChecked(): txt = '!'+txt - tok = self.FIELDS[unicode_type(self.field.currentText())]+txt + tok = self.FIELDS[str(self.field.currentText())]+txt if re.search(r'\s', tok): tok = '"%s"'%tok return tok @@ -116,25 +115,25 @@ def box_search_string(self): ans = [] self.box_last_values = {} - name = unicode_type(self.name_box.text()).strip() + name = str(self.name_box.text()).strip() if name: ans.append('name:"' + self.mc + name + '"') - description = unicode_type(self.description_box.text()).strip() + description = str(self.description_box.text()).strip() if description: ans.append('description:"' + self.mc + description + '"') - headquarters = unicode_type(self.headquarters_box.text()).strip() + headquarters = str(self.headquarters_box.text()).strip() if headquarters: ans.append('headquarters:"' + self.mc + headquarters + '"') - format = unicode_type(self.format_box.text()).strip() + format = str(self.format_box.text()).strip() if format: ans.append('format:"' + self.mc + format + '"') - enabled = unicode_type(self.enabled_combo.currentText()).strip() + enabled = str(self.enabled_combo.currentText()).strip() if enabled: ans.append('enabled:' + enabled) - drm = unicode_type(self.drm_combo.currentText()).strip() + drm = str(self.drm_combo.currentText()).strip() if drm: ans.append('drm:' + drm) - affiliate = unicode_type(self.affiliate_combo.currentText()).strip() + affiliate = str(self.affiliate_combo.currentText()).strip() if affiliate: ans.append('affiliate:' + affiliate) if ans: diff --git a/src/calibre/gui2/store/config/chooser/chooser_widget.py b/src/calibre/gui2/store/config/chooser/chooser_widget.py index 14d40cf42d..3bbcb805cb 100644 --- a/src/calibre/gui2/store/config/chooser/chooser_widget.py +++ b/src/calibre/gui2/store/config/chooser/chooser_widget.py @@ -9,7 +9,6 @@ from calibre.gui2.store.config.chooser.adv_search_builder import AdvSearchBuilderDialog from calibre.gui2.store.config.chooser.chooser_widget_ui import Ui_Form -from polyglot.builtins import unicode_type class StoreChooserWidget(QWidget, Ui_Form): @@ -31,7 +30,7 @@ def __init__(self): self.results_view.activated.connect(self.results_view.model().toggle_plugin) def do_search(self): - self.results_view.model().search(unicode_type(self.query.text())) + self.results_view.model().search(str(self.query.text())) def build_adv_search(self): adv = AdvSearchBuilderDialog(self) diff --git a/src/calibre/gui2/store/config/chooser/models.py b/src/calibre/gui2/store/config/chooser/models.py index d31dce3a7b..3a190099ff 100644 --- a/src/calibre/gui2/store/config/chooser/models.py +++ b/src/calibre/gui2/store/config/chooser/models.py @@ -16,7 +16,6 @@ from calibre.utils.config_base import prefs from calibre.utils.icu import sort_key from calibre.utils.search_query_parser import SearchQueryParser -from polyglot.builtins import unicode_type class Delegate(QStyledItemDelegate): @@ -209,7 +208,7 @@ def sort(self, col, order, reset=True): if not self.matches: return descending = order == Qt.SortOrder.DescendingOrder - self.matches.sort(key=lambda x: sort_key(unicode_type(self.data_as_text(x, col))), reverse=descending) + self.matches.sort(key=lambda x: sort_key(str(self.data_as_text(x, col))), reverse=descending) if reset: self.beginResetModel(), self.endResetModel() diff --git a/src/calibre/gui2/store/loader.py b/src/calibre/gui2/store/loader.py index a8dd3f147b..09e2740bd0 100644 --- a/src/calibre/gui2/store/loader.py +++ b/src/calibre/gui2/store/loader.py @@ -16,7 +16,7 @@ from calibre.gui2.store import StorePlugin from calibre.utils.config import JSONConfig from polyglot.urllib import urlencode -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues class VersionMismatch(ValueError): @@ -28,7 +28,7 @@ def __init__(self, ver): def download_updates(ver_map={}, server='https://code.calibre-ebook.com'): from calibre.utils.https import get_https_resource_securely - data = {k:unicode_type(v) for k, v in iteritems(ver_map)} + data = {k:str(v) for k, v in iteritems(ver_map)} data['ver'] = '1' url = '%s/stores?%s'%(server, urlencode(data)) # We use a timeout here to ensure the non-daemonic update thread does not diff --git a/src/calibre/gui2/store/search/adv_search_builder.py b/src/calibre/gui2/store/search/adv_search_builder.py index 60b1e44e9d..4412895f74 100644 --- a/src/calibre/gui2/store/search/adv_search_builder.py +++ b/src/calibre/gui2/store/search/adv_search_builder.py @@ -12,7 +12,6 @@ from calibre.gui2.store.search.adv_search_builder_ui import Ui_Dialog from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import unicode_type class AdvSearchBuilderDialog(QDialog, Ui_Dialog): @@ -84,7 +83,7 @@ def adv_search_string(self): self.mc = '=' else: self.mc = '~' - all, any, phrase, none = list(map(lambda x: unicode_type(x.text()), + all, any, phrase, none = list(map(lambda x: str(x.text()), (self.all, self.any, self.phrase, self.none))) all, any, none = list(map(self.tokens, (all, any, none))) phrase = phrase.strip() @@ -103,11 +102,11 @@ def adv_search_string(self): return ans def token(self): - txt = unicode_type(self.text.text()).strip() + txt = str(self.text.text()).strip() if txt: if self.negate.isChecked(): txt = '!'+txt - tok = self.FIELDS[unicode_type(self.field.currentText())]+txt + tok = self.FIELDS[str(self.field.currentText())]+txt if re.search(r'\s', tok): tok = '"%s"'%tok return tok @@ -123,16 +122,16 @@ def box_search_string(self): ans = [] self.box_last_values = {} - title = unicode_type(self.title_box.text()).strip() + title = str(self.title_box.text()).strip() if title: ans.append('title:"' + self.mc + title + '"') - author = unicode_type(self.author_box.text()).strip() + author = str(self.author_box.text()).strip() if author: ans.append('author:"' + self.mc + author + '"') - price = unicode_type(self.price_box.text()).strip() + price = str(self.price_box.text()).strip() if price: ans.append('price:"' + self.mc + price + '"') - format = unicode_type(self.format_box.text()).strip() + format = str(self.format_box.text()).strip() if format: ans.append('format:"' + self.mc + format + '"') drm = '' if self.drm_combo.currentIndex() == 0 else 'true' if self.drm_combo.currentIndex() == 1 else 'false' diff --git a/src/calibre/gui2/store/search/models.py b/src/calibre/gui2/store/search/models.py index a4ca73b51f..23aed7f9a8 100644 --- a/src/calibre/gui2/store/search/models.py +++ b/src/calibre/gui2/store/search/models.py @@ -18,7 +18,6 @@ CoverThreadPool from calibre.utils.icu import sort_key from calibre.utils.search_query_parser import SearchQueryParser -from polyglot.builtins import unicode_type def comparable_price(text): @@ -291,7 +290,7 @@ def sort(self, col, order, reset=True): return descending = order == Qt.SortOrder.DescendingOrder self.all_matches.sort( - key=lambda x: sort_key(unicode_type(self.data_as_text(x, col))), + key=lambda x: sort_key(str(self.data_as_text(x, col))), reverse=descending) self.reorder_matches() if reset: diff --git a/src/calibre/gui2/store/search/search.py b/src/calibre/gui2/store/search/search.py index a656ffcfe6..4a480322ec 100644 --- a/src/calibre/gui2/store/search/search.py +++ b/src/calibre/gui2/store/search/search.py @@ -22,7 +22,6 @@ CacheUpdateThreadPool from calibre.gui2.store.search.search_ui import Ui_Dialog from calibre.utils.filenames import ascii_filename -from polyglot.builtins import unicode_type class SearchDialog(QDialog, Ui_Dialog): @@ -68,7 +67,7 @@ def __init__(self, gui, parent=None, query=''): self.setup_store_checks() # Set the search query - if isinstance(query, (bytes, unicode_type)): + if isinstance(query, (bytes, str)): self.search_edit.setText(query) elif isinstance(query, dict): if 'author' in query: @@ -186,11 +185,11 @@ def do_search(self): # Don't start a search if there is nothing to search for. query = [] if self.search_title.text(): - query.append(u'title2:"~%s"' % unicode_type(self.search_title.text()).replace('"', ' ')) + query.append(u'title2:"~%s"' % str(self.search_title.text()).replace('"', ' ')) if self.search_author.text(): - query.append(u'author2:"%s"' % unicode_type(self.search_author.text()).replace('"', ' ')) + query.append(u'author2:"%s"' % str(self.search_author.text()).replace('"', ' ')) if self.search_edit.text(): - query.append(unicode_type(self.search_edit.text())) + query.append(str(self.search_edit.text())) query = " ".join(query) if not query.strip(): error_dialog(self, _('No query'), @@ -412,7 +411,7 @@ def check_progress(self): self.searching = False else: self.searching = True - if unicode_type(self.search.text()) != self.STOP_TEXT: + if str(self.search.text()) != self.STOP_TEXT: self.search.setText(self.STOP_TEXT) if not self.pi.isAnimated(): self.pi.startAnimation() @@ -436,7 +435,7 @@ def dialog_closed(self, result): self.save_state() def exec_(self): - if unicode_type(self.search_edit.text()).strip() or unicode_type(self.search_title.text()).strip() or unicode_type(self.search_author.text()).strip(): + if str(self.search_edit.text()).strip() or str(self.search_title.text()).strip() or str(self.search_author.text()).strip(): self.do_search() return QDialog.exec_(self) diff --git a/src/calibre/gui2/tag_browser/model.py b/src/calibre/gui2/tag_browser/model.py index e80f475951..35b6283d16 100644 --- a/src/calibre/gui2/tag_browser/model.py +++ b/src/calibre/gui2/tag_browser/model.py @@ -28,7 +28,7 @@ strcmp ) from calibre.utils.serialize import json_dumps, json_loads -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues TAG_SEARCH_STATES = {'clear': 0, 'mark_plus': 1, 'mark_plusplus': 2, 'mark_minus': 3, 'mark_minusminus': 4} @@ -199,7 +199,7 @@ def tag_data(self, role): else: name = tag.name if role == Qt.ItemDataRole.DisplayRole: - return unicode_type(name) + return str(name) if role == Qt.ItemDataRole.EditRole: return (tag.original_name) if role == Qt.ItemDataRole.DecorationRole: @@ -841,7 +841,7 @@ def mimeData(self, indexes): return ans def dropMimeData(self, md, action, row, column, parent): - fmts = {unicode_type(x) for x in md.formats()} + fmts = {str(x) for x in md.formats()} if not fmts.intersection(set(self.mimeTypes())): return False if "application/calibre+from_library" in fmts: @@ -1230,7 +1230,7 @@ def setData(self, index, value, role=Qt.ItemDataRole.EditRole): # set up to reposition at the same item. We can do this except if # working with the last item and that item is deleted, in which case # we position at the parent label - val = unicode_type(value or '').strip() + val = str(value or '').strip() if not val: return self.show_error_after_event_loop_tick(_('Item is blank'), _('An item cannot be set to nothing. Delete it instead.')) @@ -1291,7 +1291,7 @@ def setData(self, index, value, role=Qt.ItemDataRole.EditRole): return self.show_error_after_event_loop_tick( _('Duplicate search name'), _('The saved search name %s is already used.')%val) self.use_position_based_index_on_next_recount = True - self.db.saved_search_rename(unicode_type(item.data(role) or ''), val) + self.db.saved_search_rename(str(item.data(role) or ''), val) item.tag.name = val self.search_item_renamed.emit() # Does a refresh else: diff --git a/src/calibre/gui2/tag_browser/ui.py b/src/calibre/gui2/tag_browser/ui.py index 8670121000..6c6b65b2f5 100644 --- a/src/calibre/gui2/tag_browser/ui.py +++ b/src/calibre/gui2/tag_browser/ui.py @@ -22,7 +22,7 @@ from calibre.gui2.dialogs.tag_categories import TagCategories from calibre.gui2.dialogs.tag_list_editor import TagListEditor from calibre.gui2.dialogs.edit_authors_dialog import EditAuthorsDialog -from polyglot.builtins import unicode_type, iteritems +from polyglot.builtins import iteritems class TagBrowserMixin: # {{{ @@ -125,7 +125,7 @@ def do_add_subcategory(self, on_category_key, new_category_name=None): if new_cat not in user_cats: break i += 1 - n = new_name + unicode_type(i) + n = new_name + str(i) # Add the new category user_cats[new_cat] = [] db.new_api.set_pref('user_categories', user_cats) @@ -282,7 +282,7 @@ def do_tags_list_edit(self, tag, category, is_first_letter=False): m.delete_item_from_all_user_categories(orig_name[item], category) for old_id in to_rename: m.rename_item_in_all_user_categories(orig_name[old_id], - category, unicode_type(to_rename[old_id])) + category, str(to_rename[old_id])) db.new_api.remove_items(category, to_delete) db.new_api.rename_items(category, to_rename, change_index=False) @@ -791,7 +791,7 @@ def do_find(self, str_=None): @property def find_text(self): - return unicode_type(self.item_search.currentText()).strip() + return str(self.item_search.currentText()).strip() def reset_find(self): model = self.tags_view.model() diff --git a/src/calibre/gui2/tag_browser/view.py b/src/calibre/gui2/tag_browser/view.py index 1fba6dda41..4ecd29ed14 100644 --- a/src/calibre/gui2/tag_browser/view.py +++ b/src/calibre/gui2/tag_browser/view.py @@ -26,7 +26,6 @@ rating_font, empty_index, question_dialog) from calibre.utils.icu import sort_key from calibre.utils.serialize import json_loads -from polyglot.builtins import unicode_type class TagDelegate(QStyledItemDelegate): # {{{ @@ -81,7 +80,7 @@ def draw_text(self, style, painter, option, widget, index, item): is_search = (True if item.type == TagTreeItem.TAG and item.tag.category == 'search' else False) if not is_search and (hover or gprefs['tag_browser_show_counts']): - count = unicode_type(index.data(COUNT_ROLE)) + count = str(index.data(COUNT_ROLE)) width = painter.fontMetrics().boundingRect(count).width() r = QRect(tr) r.setRight(r.right() - 1), r.setLeft(r.right() - width - 4) @@ -244,7 +243,7 @@ def set_style_sheet(self): border: 1px solid #bfcde4; border-radius: 6px; } - '''.replace('PAD', unicode_type(gprefs['tag_browser_item_padding'])) + ( + '''.replace('PAD', str(gprefs['tag_browser_item_padding'])) + ( '' if gprefs['tag_browser_old_look'] else stylish_tb)) def set_look_and_feel(self, first=False): @@ -526,7 +525,7 @@ def context_menu_handler(self, action=None, category=None, with open(os.path.join(d, 'icon_' + sanitize_file_name(key)+'.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) - self._model.set_custom_category_icon(key, unicode_type(path)) + self._model.set_custom_category_icon(key, str(path)) self.recount() except: traceback.print_exc() @@ -726,7 +725,7 @@ def add_show_hidden_categories(): if not item.category_key.startswith('@'): while item.parent != self._model.root_item: item = item.parent - category = unicode_type(item.name or '') + category = str(item.name or '') key = item.category_key # Verify that we are working with a field that we know something about if key not in self.db.field_metadata: diff --git a/src/calibre/gui2/tag_mapper.py b/src/calibre/gui2/tag_mapper.py index c3807cd9e6..5d35351c53 100644 --- a/src/calibre/gui2/tag_mapper.py +++ b/src/calibre/gui2/tag_mapper.py @@ -18,7 +18,7 @@ from calibre.gui2.widgets2 import Dialog from calibre.utils.config import JSONConfig from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems tag_maps = JSONConfig('tag-map-rules') @@ -171,14 +171,14 @@ def rule(self): def rule(self, rule): def sc(name): c = getattr(self, name) - idx = c.findData(unicode_type(rule.get(name, ''))) + idx = c.findData(str(rule.get(name, ''))) if idx < 0: idx = 0 c.setCurrentIndex(idx) sc('action'), sc('match_type') ac = self.action.currentData() - self.query.setText(intelligent_strip(ac, unicode_type(rule.get('query', '')))) - self.replace.setText(intelligent_strip(ac, unicode_type(rule.get('replace', '')))) + self.query.setText(intelligent_strip(ac, str(rule.get('query', '')))) + self.replace.setText(intelligent_strip(ac, str(rule.get('replace', '')))) def validate(self): rule = self.rule diff --git a/src/calibre/gui2/toc/location.py b/src/calibre/gui2/toc/location.py index 7ee61d36be..1cfcb564c6 100644 --- a/src/calibre/gui2/toc/location.py +++ b/src/calibre/gui2/toc/location.py @@ -15,7 +15,6 @@ from calibre.gui2.webengine import secure_webengine from calibre.utils.logging import default_log from calibre.utils.short_uuid import uuid4 -from polyglot.builtins import unicode_type class Page(QWebEnginePage): # {{{ @@ -26,7 +25,7 @@ class Page(QWebEnginePage): # {{{ def __init__(self, prefs): self.log = default_log self.current_frag = None - self.com_id = unicode_type(uuid4()) + self.com_id = str(uuid4()) QWebEnginePage.__init__(self) secure_webengine(self.settings(), for_viewer=True) self.titleChanged.connect(self.title_changed) @@ -57,10 +56,10 @@ def __init__(self, prefs): self.scripts().insert(s) def javaScriptConsoleMessage(self, level, msg, lineno, msgid): - self.log('JS:', unicode_type(msg)) + self.log('JS:', str(msg)) def javaScriptAlert(self, origin, msg): - self.log(unicode_type(msg)) + self.log(str(msg)) def title_changed(self, title): parts = title.split('-', 1) @@ -210,7 +209,7 @@ def keyPressEvent(self, ev): return super(ItemEdit, self).keyPressEvent(ev) def find(self, forwards=True): - text = unicode_type(self.search_text.text()).strip() + text = str(self.search_text.text()).strip() flags = QWebEnginePage.FindFlags(0) if forwards else QWebEnginePage.FindFlag.FindBackward self.find_data = text, flags, forwards self.view.findText(text, flags, self.find_callback) @@ -224,9 +223,9 @@ def find_callback(self, found): _('No match found for: %s')%text, show=True) delta = 1 if forwards else -1 - current = unicode_type(d.currentItem().data(Qt.ItemDataRole.DisplayRole) or '') + current = str(d.currentItem().data(Qt.ItemDataRole.DisplayRole) or '') next_index = (d.currentRow() + delta)%d.count() - next = unicode_type(d.item(next_index).data(Qt.ItemDataRole.DisplayRole) or '') + next = str(d.item(next_index).data(Qt.ItemDataRole.DisplayRole) or '') msg = '

    '+_('No matches for %(text)s found in the current file [%(current)s].' ' Do you want to search in the %(which)s file [%(next)s]?') msg = msg%dict(text=text, current=current, next=next, @@ -249,7 +248,7 @@ def load(self, container): self.dest_list.addItems(spine_names) def current_changed(self, item): - name = self.current_name = unicode_type(item.data(Qt.ItemDataRole.DisplayRole) or '') + name = self.current_name = str(item.data(Qt.ItemDataRole.DisplayRole) or '') path = self.container.name_to_abspath(name) # Ensure encoding map is populated root = self.container.parsed(name) @@ -281,7 +280,7 @@ def __call__(self, item, where): if toc.dest: for i in range(self.dest_list.count()): litem = self.dest_list.item(i) - if unicode_type(litem.data(Qt.ItemDataRole.DisplayRole) or '') == toc.dest: + if str(litem.data(Qt.ItemDataRole.DisplayRole) or '') == toc.dest: dest_index = i frag = toc.frag break diff --git a/src/calibre/gui2/toc/main.py b/src/calibre/gui2/toc/main.py index fa67e46d1f..c0837a84b5 100644 --- a/src/calibre/gui2/toc/main.py +++ b/src/calibre/gui2/toc/main.py @@ -33,7 +33,6 @@ from calibre.utils.config import JSONConfig from calibre.utils.filenames import atomic_rename from calibre.utils.logging import GUILog -from polyglot.builtins import unicode_type ICON_SIZE = 24 @@ -86,11 +85,11 @@ def save_settings(self): name, ok = QInputDialog.getText(self, _('Choose name'), _('Choose a name for these settings')) if ok: - name = unicode_type(name).strip() + name = str(name).strip() if name: saved = self.prefs.get('xpath_toc_settings', {}) # in JSON all keys have to be strings - saved[name] = {unicode_type(i):x for i, x in enumerate(xpaths)} + saved[name] = {str(i):x for i, x in enumerate(xpaths)} self.prefs.set('xpath_toc_settings', saved) self.setup_load_button() @@ -113,7 +112,7 @@ def clear_settings(self): def load_settings(self, name): saved = self.prefs.get('xpath_toc_settings', {}).get(name, {}) for i, w in enumerate(self.widgets): - txt = saved.get(unicode_type(i), '') + txt = saved.get(str(i), '') w.edit.setText(txt) def check(self): @@ -357,7 +356,7 @@ def __call__(self, item): def populate_item_pane(self): item = self.current_item - name = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + name = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') self.item_pane.heading.setText('

    %s

    '%name) self.icon_label.setPixmap(item.data(0, Qt.ItemDataRole.DecorationRole ).pixmap(32, 32)) @@ -601,33 +600,33 @@ def title_case(self): self.push_history() from calibre.utils.titlecase import titlecase for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') item.setData(0, Qt.ItemDataRole.DisplayRole, titlecase(t)) def upper_case(self): self.push_history() for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') item.setData(0, Qt.ItemDataRole.DisplayRole, icu_upper(t)) def lower_case(self): self.push_history() for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') item.setData(0, Qt.ItemDataRole.DisplayRole, icu_lower(t)) def swap_case(self): self.push_history() from calibre.utils.icu import swapcase for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') item.setData(0, Qt.ItemDataRole.DisplayRole, swapcase(t)) def capitalize(self): self.push_history() from calibre.utils.icu import capitalize for item in self.selectedItems(): - t = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') item.setData(0, Qt.ItemDataRole.DisplayRole, capitalize(t)) def bulk_rename(self): @@ -665,7 +664,7 @@ def show_context_menu(self, point): item = self.currentItem() def key(k): - sc = unicode_type(QKeySequence(k | Qt.Modifier.CTRL).toString(QKeySequence.SequenceFormat.NativeText)) + sc = str(QKeySequence(k | Qt.Modifier.CTRL).toString(QKeySequence.SequenceFormat.NativeText)) return ' [%s]'%sc if item is not None: @@ -674,7 +673,7 @@ def key(k): m.addAction(QIcon(I('modified.png')), _('Bulk rename all selected items'), self.bulk_rename) m.addAction(QIcon(I('trash.png')), _('Remove all selected items'), self.del_items) m.addSeparator() - ci = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + ci = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') p = item.parent() or self.invisibleRootItem() idx = p.indexOfChild(item) if idx > 0: @@ -775,12 +774,12 @@ def edit_item(self): def event(self, e): if e.type() == QEvent.Type.StatusTip: - txt = unicode_type(e.tip()) or self.default_msg + txt = str(e.tip()) or self.default_msg self.hl.setText(txt) return super(TOCView, self).event(e) def item_title(self, item): - return unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '') + return str(item.data(0, Qt.ItemDataRole.DisplayRole) or '') def del_items(self): self.tocw.del_items() @@ -835,7 +834,7 @@ def move_down(self): def data_changed(self, top_left, bottom_right): for r in range(top_left.row(), bottom_right.row()+1): idx = self.tocw.model().index(r, 0, top_left.parent()) - new_title = unicode_type(idx.data(Qt.ItemDataRole.DisplayRole) or '').strip() + new_title = str(idx.data(Qt.ItemDataRole.DisplayRole) or '').strip() toc = idx.data(Qt.ItemDataRole.UserRole) if toc is not None: toc.title = new_title or _('(Untitled)') @@ -927,7 +926,7 @@ def create_toc(self): def process_node(parent, toc_parent): for i in range(parent.childCount()): item = parent.child(i) - title = unicode_type(item.data(0, Qt.ItemDataRole.DisplayRole) or '').strip() + title = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '').strip() toc = item.data(0, Qt.ItemDataRole.UserRole) dest, frag = toc.dest, toc.frag toc = toc_parent.add(title, dest, frag) diff --git a/src/calibre/gui2/tools.py b/src/calibre/gui2/tools.py index d2874a0cea..3612b70f07 100644 --- a/src/calibre/gui2/tools.py +++ b/src/calibre/gui2/tools.py @@ -24,7 +24,7 @@ GuiRecommendations, load_defaults, load_specifics, save_specifics, get_input_format_for_book, NoSupportedInputFormats) from calibre.gui2.convert import bulk_defaults_for_input_format -from polyglot.builtins import unicode_type, as_bytes +from polyglot.builtins import as_bytes def convert_single_ebook(parent, db, book_ids, auto_conversion=False, # {{{ @@ -67,7 +67,7 @@ def convert_single_ebook(parent, db, book_ids, auto_conversion=False, # {{{ temp_files = [in_file] try: - dtitle = unicode_type(mi.title) + dtitle = str(mi.title) except: dtitle = repr(mi.title) desc = _('Convert book %(num)d of %(total)d (%(title)s)') % \ @@ -228,7 +228,7 @@ def do_book(self): if x[0] == 'debug_pipeline': lrecs.remove(x) try: - dtitle = unicode_type(mi.title) + dtitle = str(mi.title) except: dtitle = repr(mi.title) if len(dtitle) > 50: diff --git a/src/calibre/gui2/tweak_book/boss.py b/src/calibre/gui2/tweak_book/boss.py index b0f4492796..24eba47f55 100644 --- a/src/calibre/gui2/tweak_book/boss.py +++ b/src/calibre/gui2/tweak_book/boss.py @@ -69,7 +69,7 @@ from calibre.utils.icu import numeric_sort_key from calibre.utils.imghdr import identify from calibre.utils.tdir_in_cache import tdir_in_cache -from polyglot.builtins import as_bytes, iteritems, itervalues, string_or_bytes, unicode_type +from polyglot.builtins import as_bytes, iteritems, itervalues, string_or_bytes from polyglot.urllib import urlparse _diff_dialogs = [] @@ -388,7 +388,7 @@ def book_opened(self, job): import traceback traceback.print_exc() if ef: - if isinstance(ef, unicode_type): + if isinstance(ef, str): ef = [ef] tuple(map(self.gui.file_list.request_edit, ef)) else: diff --git a/src/calibre/gui2/tweak_book/char_select.py b/src/calibre/gui2/tweak_book/char_select.py index ac3832945c..3cfebad1f2 100644 --- a/src/calibre/gui2/tweak_book/char_select.py +++ b/src/calibre/gui2/tweak_book/char_select.py @@ -22,7 +22,6 @@ from calibre.utils.icu import safe_chr as codepoint_to_chr from calibre.utils.unicode_names import character_name_from_code, points_for_word from calibre_extensions.progress_indicator import set_no_activate_on_click -from polyglot.builtins import unicode_type ROOT = QModelIndex() @@ -519,7 +518,7 @@ def mimeTypes(self): return ['application/calibre_charcode_indices'] def mimeData(self, indexes): - data = ','.join(unicode_type(i.row()) for i in indexes) + data = ','.join(str(i.row()) for i in indexes) md = QMimeData() md.setData('application/calibre_charcode_indices', data.encode('utf-8')) return md @@ -763,7 +762,7 @@ def setup_ui(self): self.char_view.setFocus(Qt.FocusReason.OtherFocusReason) def do_search(self): - text = unicode_type(self.search.text()).strip() + text = str(self.search.text()).strip() if not text: return self.clear_search() with BusyCursor(): diff --git a/src/calibre/gui2/tweak_book/check.py b/src/calibre/gui2/tweak_book/check.py index b5470aad7b..887135c319 100644 --- a/src/calibre/gui2/tweak_book/check.py +++ b/src/calibre/gui2/tweak_book/check.py @@ -17,7 +17,6 @@ from calibre.gui2 import NO_URL_FORMATTING, safe_open_url from calibre.gui2.tweak_book import tprefs from calibre.gui2.tweak_book.widgets import BusyCursor -from polyglot.builtins import unicode_type def icon_for_level(level): @@ -101,7 +100,7 @@ def context_menu(self, pos): def copy_to_clipboard(self): items = [] for item in (self.items.item(i) for i in range(self.items.count())): - msg = unicode_type(item.text()) + msg = str(item.text()) msg = prefix_for_level(item.data(Qt.ItemDataRole.UserRole).level) + msg items.append(msg) if items: @@ -117,7 +116,7 @@ def clear_help(self, msg=None): msg, _('Click to run a check on the book'), _('Run check'))) def link_clicked(self, url): - url = unicode_type(url.toString(NO_URL_FORMATTING)) + url = str(url.toString(NO_URL_FORMATTING)) if url == 'activate:item': self.current_item_activated() elif url == 'run:check': diff --git a/src/calibre/gui2/tweak_book/completion/basic.py b/src/calibre/gui2/tweak_book/completion/basic.py index a0df293ee9..953e041179 100644 --- a/src/calibre/gui2/tweak_book/completion/basic.py +++ b/src/calibre/gui2/tweak_book/completion/basic.py @@ -20,7 +20,7 @@ from calibre.utils.ipc import eintr_retry_call from calibre.utils.matcher import Matcher from calibre.utils.icu import numeric_sort_key -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues Request = namedtuple('Request', 'id type data query') @@ -66,10 +66,10 @@ def get_data(data_conn, data_type, data=None): return result -class Name(unicode_type): +class Name(str): def __new__(self, name, mime_type, spine_names): - ans = unicode_type.__new__(self, name) + ans = str.__new__(self, name) ans.mime_type = mime_type ans.in_spine = name in spine_names return ans @@ -112,7 +112,7 @@ def create_anchor_map(root): def complete_anchor(name, data_conn): if name not in file_cache: data = raw = get_data(data_conn, 'file_data', name) - if isinstance(raw, unicode_type): + if isinstance(raw, str): try: root = parse(raw, decoder=lambda x:x.decode('utf-8')) except Exception: diff --git a/src/calibre/gui2/tweak_book/completion/utils.py b/src/calibre/gui2/tweak_book/completion/utils.py index 6270a5a6a5..d071fb8fb4 100644 --- a/src/calibre/gui2/tweak_book/completion/utils.py +++ b/src/calibre/gui2/tweak_book/completion/utils.py @@ -2,7 +2,6 @@ # vim:fileencoding=utf-8 -from polyglot.builtins import unicode_type __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal ' @@ -25,4 +24,4 @@ def __init__(self, tb, msg=None): self.tb = tb def traceback(self): - return unicode_type(self) + '\n' + self.tb + return str(self) + '\n' + self.tb diff --git a/src/calibre/gui2/tweak_book/diff/main.py b/src/calibre/gui2/tweak_book/diff/main.py index 23fef397a5..5d6ae1a223 100644 --- a/src/calibre/gui2/tweak_book/diff/main.py +++ b/src/calibre/gui2/tweak_book/diff/main.py @@ -23,7 +23,7 @@ from calibre.gui2.widgets2 import HistoryLineEdit2 from calibre.utils.filenames import samefile from calibre.utils.icu import numeric_sort_key -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class BusyWidget(QWidget): # {{{ @@ -131,7 +131,7 @@ def get_decoded_raw(name): def string_diff(left, right, left_syntax=None, right_syntax=None, left_name='left', right_name='right'): - left, right = unicode_type(left), unicode_type(right) + left, right = str(left), str(right) cache = Cache() cache.set_left(left_name, left), cache.set_right(right_name, right) changed_names = {} if left == right else {left_name:right_name} @@ -324,7 +324,7 @@ def break_cycles(self): pass def do_search(self, reverse): - text = unicode_type(self.search.text()) + text = str(self.search.text()) if not text.strip(): return v = self.view.view.left if self.lb.isChecked() else self.view.view.right diff --git a/src/calibre/gui2/tweak_book/diff/view.py b/src/calibre/gui2/tweak_book/diff/view.py index 012aac1891..007e843830 100644 --- a/src/calibre/gui2/tweak_book/diff/view.py +++ b/src/calibre/gui2/tweak_book/diff/view.py @@ -28,7 +28,7 @@ from calibre.gui2.tweak_book.editor.themes import get_theme, theme_color from calibre.utils.icu import utf16_length from calibre.utils.xml_parse import safe_xml_fromstring -from polyglot.builtins import as_bytes, iteritems, unicode_type +from polyglot.builtins import as_bytes, iteritems Change = namedtuple('Change', 'ltop lbot rtop rbot kind') @@ -81,7 +81,7 @@ def __new__(cls): return self def __setitem__(self, k, v): - v = unicode_type(v) + v = str(v) dict.__setitem__(self, k, v) self.max_width = max(self.max_width, len(v)) @@ -162,13 +162,13 @@ def __init__(self, right=False, parent=None, show_open_in_editor=False): def calculate_metrics(self): w = self.fontMetrics() - self.number_width = max(map(lambda x:w.width(unicode_type(x)), range(10))) + self.number_width = max(map(lambda x:w.width(str(x)), range(10))) self.space_width = w.width(' ') def show_context_menu(self, pos): m = QMenu(self) a = m.addAction - i = unicode_type(self.textCursor().selectedText()).rstrip('\0') + i = str(self.textCursor().selectedText()).rstrip('\0') if i: a(QIcon(I('edit-copy.png')), _('Copy to clipboard'), self.copy).setShortcut(QKeySequence.StandardKey.Copy) @@ -217,7 +217,7 @@ def search(self, query, reverse=False): headers = dict(self.headers) if lnum in headers: cpos = self.search_header_pos - lines = unicode_type(self.toPlainText()).splitlines() + lines = str(self.toPlainText()).splitlines() for hn, text in self.headers: lines[hn] = text prefix, postfix = lines[lnum][:cpos], lines[lnum][cpos:] @@ -308,7 +308,7 @@ def paint_line_numbers(self, ev): while block.isValid() and top <= ev.rect().bottom(): r = ev.rect() if block.isVisible() and bottom >= r.top(): - text = unicode_type(self.line_number_map.get(num, '')) + text = str(self.line_number_map.get(num, '')) is_start = text != '-' and num in change_starts if is_start: painter.save() @@ -531,7 +531,7 @@ def finalize(self): def add_diff(self, left_name, right_name, left_text, right_text, context=None, syntax=None, beautify=False): left_text, right_text = left_text or '', right_text or '' is_identical = len(left_text) == len(right_text) and left_text == right_text and left_name == right_name - is_text = isinstance(left_text, unicode_type) and isinstance(right_text, unicode_type) + is_text = isinstance(left_text, str) and isinstance(right_text, str) left_name = left_name or '[%s]'%_('This file was added') right_name = right_name or '[%s]'%_('This file was removed') self.left.headers.append((self.left.blockCount() - 1, left_name)) diff --git a/src/calibre/gui2/tweak_book/editor/insert_resource.py b/src/calibre/gui2/tweak_book/editor/insert_resource.py index 6901b1aee8..d03f3234c7 100644 --- a/src/calibre/gui2/tweak_book/editor/insert_resource.py +++ b/src/calibre/gui2/tweak_book/editor/insert_resource.py @@ -27,7 +27,6 @@ from calibre.utils.icu import numeric_sort_key from calibre.utils.localization import canonicalize_lang, get_lang from calibre_extensions.progress_indicator import set_no_activate_on_click -from polyglot.builtins import unicode_type class ChooseName(Dialog): # {{{ @@ -59,13 +58,13 @@ def show_error(self, msg): return False def verify(self): - return name_is_ok(unicode_type(self.name_edit.text()), self.show_error) + return name_is_ok(str(self.name_edit.text()), self.show_error) def accept(self): if not self.verify(): return error_dialog(self, _('No name specified'), _( 'You must specify a file name for the new file, with an extension.'), show=True) - n = unicode_type(self.name_edit.text()).replace('\\', '/') + n = str(self.name_edit.text()).replace('\\', '/') name, ext = n.rpartition('.')[0::2] self.filename = name + '.' + ext.lower() super(ChooseName, self).accept() @@ -111,7 +110,7 @@ def sizeHint(self, option, index): def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, empty_index) # draw the hover and selection highlights - name = unicode_type(index.data(Qt.ItemDataRole.DisplayRole) or '') + name = str(index.data(Qt.ItemDataRole.DisplayRole) or '') cover = self.cover_cache.get(name, None) if cover is None: cover = self.cover_cache[name] = QPixmap() @@ -338,16 +337,16 @@ def pressed(self, index): def activated(self, index): if self.for_browsing: - return self.image_activated.emit(unicode_type(index.data() or '')) + return self.image_activated.emit(str(index.data() or '')) self.chosen_image_is_external = False self.accept() def accept(self): - self.chosen_image = unicode_type(self.view.currentIndex().data() or '') + self.chosen_image = str(self.view.currentIndex().data() or '') super(InsertImage, self).accept() def filter_changed(self, *args): - f = unicode_type(self.filter.text()) + f = str(self.filter.text()) self.fm.setFilterFixedString(f) # }}} @@ -416,8 +415,8 @@ def show_context_menu(self, point): def create_folder(self, item): text, ok = QInputDialog.getText(self, _('Folder name'), _('Enter a name for the new folder')) - if ok and unicode_type(text): - c = QTreeWidgetItem(item, (unicode_type(text),)) + if ok and str(text): + c = QTreeWidgetItem(item, (str(text),)) c.setIcon(0, QIcon(I('mimetypes/dir.png'))) for item in self.folders.selectedItems(): item.setSelected(False) @@ -427,7 +426,7 @@ def create_folder(self, item): def folder_path(self, item): ans = [] while item is not self.root: - ans.append(unicode_type(item.text(0))) + ans.append(str(item.text(0))) item = item.parent() return tuple(reversed(ans)) @@ -476,15 +475,15 @@ def set_fmt(self, fmt): def accept(self): with tprefs: - tprefs.set('previous_new_book_authors', unicode_type(self.authors.text())) + tprefs.set('previous_new_book_authors', str(self.authors.text())) tprefs.set('previous_new_book_lang', (self.languages.lang_codes or [get_lang()])[0]) self.languages.update_recently_used() super(NewBook, self).accept() @property def mi(self): - mi = Metadata(unicode_type(self.title.text()).strip() or _('Unknown')) - mi.authors = string_to_authors(unicode_type(self.authors.text()).strip()) or [_('Unknown')] + mi = Metadata(str(self.title.text()).strip() or _('Unknown')) + mi.authors = string_to_authors(str(self.authors.text()).strip()) or [_('Unknown')] mi.languages = self.languages.lang_codes or [get_lang()] return mi diff --git a/src/calibre/gui2/tweak_book/editor/smarts/html.py b/src/calibre/gui2/tweak_book/editor/smarts/html.py index a5f72dd05f..b344025b99 100644 --- a/src/calibre/gui2/tweak_book/editor/smarts/html.py +++ b/src/calibre/gui2/tweak_book/editor/smarts/html.py @@ -27,7 +27,6 @@ ATTR_END, ATTR_NAME, ATTR_START, ATTR_VALUE ) from calibre.utils.icu import utf16_length -from polyglot.builtins import unicode_type get_offset = itemgetter(0) PARAGRAPH_SEPARATOR = '\u2029' @@ -354,10 +353,10 @@ def add_tag(tag): a = QTextEdit.ExtraSelection() a.cursor, a.format = editor.textCursor(), editor.match_paren_format a.cursor.setPosition(tag.start_block.position()), a.cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor) - text = unicode_type(a.cursor.selectedText()) + text = str(a.cursor.selectedText()) start_pos = utf16_length(text[:tag.start_offset]) a.cursor.setPosition(tag.end_block.position()), a.cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor) - text = unicode_type(a.cursor.selectedText()) + text = str(a.cursor.selectedText()) end_pos = utf16_length(text[:tag.end_offset + 1]) a.cursor.setPosition(tag.start_block.position() + start_pos) a.cursor.setPosition(tag.end_block.position() + end_pos, QTextCursor.MoveMode.KeepAnchor) diff --git a/src/calibre/gui2/tweak_book/editor/snippets.py b/src/calibre/gui2/tweak_book/editor/snippets.py index 8ac4be5c52..b008fb0298 100644 --- a/src/calibre/gui2/tweak_book/editor/snippets.py +++ b/src/calibre/gui2/tweak_book/editor/snippets.py @@ -25,9 +25,9 @@ from calibre.utils.config import JSONConfig from calibre.utils.icu import string_length as strlen from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import codepoint_to_chr, iteritems, itervalues, unicode_type +from polyglot.builtins import codepoint_to_chr, iteritems, itervalues -string_length = lambda x: strlen(unicode_type(x)) # Needed on narrow python builds, as subclasses of unicode dont work +string_length = lambda x: strlen(str(x)) # Needed on narrow python builds, as subclasses of unicode dont work KEY = Qt.Key.Key_J MODIFIER = Qt.Modifier.META if ismacos else Qt.Modifier.CTRL @@ -105,7 +105,7 @@ def escape_funcs(): return escape, unescape -class TabStop(unicode_type): +class TabStop(str): def __new__(self, raw, start_offset, tab_stops, is_toplevel=True): if raw.endswith('}'): @@ -116,7 +116,7 @@ def __new__(self, raw, start_offset, tab_stops, is_toplevel=True): for c in child_stops: c.parent = self tab_stops.extend(child_stops) - self = unicode_type.__new__(self, uraw) + self = str.__new__(self, uraw) if num.endswith('*'): self.takes_selection = True num = num[:-1] @@ -124,7 +124,7 @@ def __new__(self, raw, start_offset, tab_stops, is_toplevel=True): self.takes_selection = False self.num = int(num) else: - self = unicode_type.__new__(self, '') + self = str.__new__(self, '') self.num = int(raw[1:]) self.takes_selection = False self.start = start_offset @@ -136,7 +136,7 @@ def __new__(self, raw, start_offset, tab_stops, is_toplevel=True): def __repr__(self): return 'TabStop(text=%s num=%d start=%d is_mirror=%s takes_selection=%s is_toplevel=%s)' % ( - unicode_type.__repr__(self), self.num, self.start, self.is_mirror, self.takes_selection, self.is_toplevel) + str.__repr__(self), self.num, self.start, self.is_mirror, self.takes_selection, self.is_toplevel) def parse_template(template, start_offset=0, is_toplevel=True, grouped=True): @@ -175,7 +175,7 @@ def snippets(refresh=False): if _snippets is None or refresh: _snippets = copy.deepcopy(builtin_snippets) for snip in user_snippets.get('snippets', []): - if snip['trigger'] and isinstance(snip['trigger'], unicode_type): + if snip['trigger'] and isinstance(snip['trigger'], str): key = snip_key(snip['trigger'], *snip['syntaxes']) _snippets[key] = {'template':snip['template'], 'description':snip['description']} _snippets = sorted(iteritems(_snippets), key=(lambda key_snip:string_length(key_snip[0].trigger)), reverse=True) diff --git a/src/calibre/gui2/tweak_book/editor/syntax/base.py b/src/calibre/gui2/tweak_book/editor/syntax/base.py index ea83678d06..ce0edd6711 100644 --- a/src/calibre/gui2/tweak_book/editor/syntax/base.py +++ b/src/calibre/gui2/tweak_book/editor/syntax/base.py @@ -11,7 +11,7 @@ from ..themes import highlight_to_char_format from calibre.gui2.tweak_book.widgets import BusyCursor from calibre.utils.icu import utf16_length -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def run_loop(user_data, state_map, formats, text): @@ -215,7 +215,7 @@ def parse_single_block(self, block): start_state = self.user_data_factory().state ud.clear(state=start_state, doc_name=self.doc_name) # Ensure no stale user data lingers formats = [] - for i, num, fmt in run_loop(ud, self.state_map, self.formats, unicode_type(block.text())): + for i, num, fmt in run_loop(ud, self.state_map, self.formats, str(block.text())): if fmt is not None: r = QTextLayout.FormatRange() r.start, r.length, r.format = i, num, fmt diff --git a/src/calibre/gui2/tweak_book/editor/text.py b/src/calibre/gui2/tweak_book/editor/text.py index b5df71b528..53249cce65 100644 --- a/src/calibre/gui2/tweak_book/editor/text.py +++ b/src/calibre/gui2/tweak_book/editor/text.py @@ -40,7 +40,7 @@ ) from calibre.utils.img import image_to_data from calibre.utils.titlecase import titlecase -from polyglot.builtins import as_unicode, unicode_type +from polyglot.builtins import as_unicode def get_highlighter(syntax): @@ -67,7 +67,7 @@ def get_smarts(syntax): def default_font_family(): global _dff if _dff is None: - families = set(map(unicode_type, QFontDatabase().families())) + families = set(map(str, QFontDatabase().families())) for x in ('Ubuntu Mono', 'Consolas', 'Liberation Mono'): if x in families: _dff = x @@ -260,7 +260,7 @@ def apply_theme(self, theme): self.setFont(font) self.highlighter.apply_theme(theme) w = self.fontMetrics() - self.number_width = max(map(lambda x:w.width(unicode_type(x)), range(10))) + self.number_width = max(map(lambda x:w.width(str(x)), range(10))) self.size_hint = QSize(self.expected_geometry[0] * w.averageCharWidth(), self.expected_geometry[1] * w.height()) self.highlight_color = theme_color(theme, 'HighlightRegion', 'bg') self.highlight_cursor_line() @@ -280,7 +280,7 @@ def load_text(self, text, syntax='html', process_template=False, doc_name=None): self.setTabStopWidth(self.tw * self.space_width) if isinstance(text, bytes): text = text.decode('utf-8', 'replace') - self.setPlainText(unicodedata.normalize('NFC', unicode_type(text))) + self.setPlainText(unicodedata.normalize('NFC', str(text))) if process_template and QPlainTextEdit.find(self, '%CURSOR%'): c = self.textCursor() c.insertText('') @@ -314,7 +314,7 @@ def go_to_line(self, lnum, col=None): c.movePosition(QTextCursor.MoveOperation.NextBlock, n=lnum - 1) c.movePosition(QTextCursor.MoveOperation.StartOfLine) c.movePosition(QTextCursor.MoveOperation.EndOfLine, QTextCursor.MoveMode.KeepAnchor) - text = unicode_type(c.selectedText()).rstrip('\0') + text = str(c.selectedText()).rstrip('\0') if col is None: c.movePosition(QTextCursor.MoveOperation.StartOfLine) lt = text.lstrip() @@ -373,7 +373,7 @@ def find_in_marked(self, pat, wrap=False, save_match=None): if wrap: pos = m_end if reverse else m_start c.setPosition(pos, QTextCursor.MoveMode.KeepAnchor) - raw = unicode_type(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') + raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.search(raw) if m is None: return False @@ -406,7 +406,7 @@ def all_in_marked(self, pat, template=None): if self.current_search_mark is None: return 0 c = self.current_search_mark.cursor - raw = unicode_type(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') + raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') if template is None: count = len(pat.findall(raw)) else: @@ -420,7 +420,7 @@ def all_in_marked(self, pat, template=None): if getattr(template.func, 'append_final_output_to_marked', False): retval = template.end() if retval: - raw += unicode_type(retval) + raw += str(retval) else: template.end() show_function_debug_output(template) @@ -443,7 +443,7 @@ def sort_css(self): c = self.textCursor() c.beginEditBlock() c.movePosition(QTextCursor.MoveOperation.Start), c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor) - text = unicode_type(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') + text = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') from calibre.ebooks.oeb.polish.css import sort_sheet text = css_text(sort_sheet(current_container(), text)) c.insertText(text) @@ -464,7 +464,7 @@ def find(self, pat, wrap=False, marked=False, complete=False, save_match=None): if wrap and not complete: pos = QTextCursor.MoveOperation.End if reverse else QTextCursor.MoveOperation.Start c.movePosition(pos, QTextCursor.MoveMode.KeepAnchor) - raw = unicode_type(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') + raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.search(raw) if m is None: return False @@ -509,7 +509,7 @@ def find_text(self, pat, wrap=False, complete=False): if not found: return False else: - raw = unicode_type(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') + raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.search(raw) if m is None: return False @@ -542,7 +542,7 @@ def find_first_word(haystack): return match_pos, match_word while True: - text = unicode_type(c.selectedText()).rstrip('\0') + text = str(c.selectedText()).rstrip('\0') idx, word = find_first_word(text) if idx == -1: return False @@ -579,7 +579,7 @@ def find_next_spell_error(self, from_cursor=True): def replace(self, pat, template, saved_match='gui'): c = self.textCursor() - raw = unicode_type(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') + raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.fullmatch(raw) if m is None: # This can happen if either the user changed the selected text or @@ -606,7 +606,7 @@ def go_to_anchor(self, anchor): self.setTextCursor(c) return True base = r'''%%s\s*=\s*['"]{0,1}%s''' % regex.escape(anchor) - raw = unicode_type(self.toPlainText()) + raw = str(self.toPlainText()) m = regex.search(base % 'id', raw) if m is None: m = regex.search(base % 'name', raw) @@ -685,7 +685,7 @@ def paint_line_numbers(self, ev): painter.setFont(f) self.last_current_lnum = (top, bottom - top) painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(), - Qt.AlignmentFlag.AlignRight, unicode_type(num + 1)) + Qt.AlignmentFlag.AlignRight, str(num + 1)) if current == num: painter.restore() block = block.next() @@ -751,7 +751,7 @@ def show_tooltip(self, ev): fmt_range = self.syntax_range_for_cursor(c) fmt = getattr(fmt_range, 'format', None) if fmt is not None: - tt = unicode_type(fmt.toolTip()) + tt = str(fmt.toolTip()) if tt: QToolTip.setFont(self.tooltip_font) QToolTip.setPalette(self.tooltip_palette) @@ -830,7 +830,7 @@ def get_range_inside_tag(self): right = max(c.anchor(), c.position()) # For speed we use QPlainTextEdit's toPlainText as we dont care about # spaces in this context - raw = unicode_type(QPlainTextEdit.toPlainText(self)) + raw = str(QPlainTextEdit.toPlainText(self)) # Make sure the left edge is not within a <> gtpos = raw.find('>', left) ltpos = raw.find('<', left) @@ -876,7 +876,7 @@ def format_text(self, formatting): c = self.textCursor() c.setPosition(left) c.setPosition(right, QTextCursor.MoveMode.KeepAnchor) - prev_text = unicode_type(c.selectedText()).rstrip('\0') + prev_text = str(c.selectedText()).rstrip('\0') c.insertText(prefix + prev_text + suffix) if prev_text: right = c.position() @@ -983,10 +983,10 @@ def replace_possible_unicode_sequence(self): c = self.textCursor() has_selection = c.hasSelection() if has_selection: - text = unicode_type(c.selectedText()).rstrip('\0') + text = str(c.selectedText()).rstrip('\0') else: c.setPosition(c.position() - min(c.positionInBlock(), 6), QTextCursor.MoveMode.KeepAnchor) - text = unicode_type(c.selectedText()).rstrip('\0') + text = str(c.selectedText()).rstrip('\0') m = re.search(r'[a-fA-F0-9]{2,6}$', text) if m is None: return False @@ -1032,7 +1032,7 @@ def goto_css_rule(self, rule_address, sourceline_address=None): from calibre.gui2.tweak_book.editor.smarts.css import find_rule block = None if self.syntax == 'css': - raw = unicode_type(self.toPlainText()) + raw = str(self.toPlainText()) line, col = find_rule(raw, rule_address) if line is not None: block = self.document().findBlockByNumber(line - 1) diff --git a/src/calibre/gui2/tweak_book/editor/themes.py b/src/calibre/gui2/tweak_book/editor/themes.py index f18610df3e..5f79118732 100644 --- a/src/calibre/gui2/tweak_book/editor/themes.py +++ b/src/calibre/gui2/tweak_book/editor/themes.py @@ -17,7 +17,7 @@ from calibre.gui2.tweak_book import tprefs from calibre.gui2.tweak_book.editor import syntax_text_char_format from calibre.gui2.tweak_book.widgets import Dialog -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems underline_styles = {'single', 'dash', 'dot', 'dash_dot', 'dash_dot_dot', 'wave', 'spell'} @@ -346,7 +346,7 @@ def setup_ui(self): @property def theme_name(self): - return unicode_type(self._name.text()).strip() + return str(self._name.text()).strip() def accept(self): if not self.theme_name: @@ -475,7 +475,7 @@ def create_color_button(key, text): l.addStretch(1) def us_changed(self): - self.data['underline'] = unicode_type(self.underline.currentText()) or None + self.data['underline'] = str(self.underline.currentText()) or None self.changed.emit() # Help text {{{ @@ -619,7 +619,7 @@ def update_theme(self, name): data[k] = dict(THEMES[default_theme()][k]._asdict()) for nk, nv in iteritems(data[k]): if isinstance(nv, QBrush): - data[k][nk] = unicode_type(nv.color().name()) + data[k][nk] = str(nv.color().name()) if extra or missing: tprefs['custom_themes'][name] = data return data @@ -633,7 +633,7 @@ def show_theme(self): c.setParent(None) c.deleteLater() self.properties = [] - name = unicode_type(self.theme.currentText()) + name = str(self.theme.currentText()) if not name: return data = self.update_theme(name) @@ -650,7 +650,7 @@ def show_theme(self): @property def theme_name(self): - return unicode_type(self.theme.currentText()) + return str(self.theme.currentText()) def changed(self): name = self.theme_name @@ -661,7 +661,7 @@ def create_new_theme(self): d = CreateNewTheme(self) if d.exec_() == QDialog.DialogCode.Accepted: name = '*' + d.theme_name - base = unicode_type(d.base.currentText()) + base = str(d.base.currentText()) theme = {} for key, val in iteritems(THEMES[base]): theme[key] = {k:col_to_string(v.color()) if isinstance(v, QBrush) else v for k, v in iteritems(val._asdict())} diff --git a/src/calibre/gui2/tweak_book/editor/widget.py b/src/calibre/gui2/tweak_book/editor/widget.py index 417e8de43b..ed027ef013 100644 --- a/src/calibre/gui2/tweak_book/editor/widget.py +++ b/src/calibre/gui2/tweak_book/editor/widget.py @@ -29,7 +29,7 @@ from calibre.gui2.tweak_book.editor.help import help_url from calibre.gui2.tweak_book.editor.text import TextEdit from calibre.utils.icu import utf16_length -from polyglot.builtins import itervalues, string_or_bytes, unicode_type +from polyglot.builtins import itervalues, string_or_bytes def create_icon(text, palette=None, sz=None, divider=2, fill='white'): @@ -224,7 +224,7 @@ def change_document_name(self, newname): def get_raw_data(self): # The EPUB spec requires NFC normalization, see section 1.3.6 of # http://www.idpf.org/epub/20/spec/OPS_2.0.1_draft.htm - return unicodedata.normalize('NFC', unicode_type(self.editor.toPlainText()).rstrip('\0')) + return unicodedata.normalize('NFC', str(self.editor.toPlainText()).rstrip('\0')) def replace_data(self, raw, only_if_different=True): if isinstance(raw, bytes): @@ -485,7 +485,7 @@ def cursor_position(self): if not c.atStart(): c.clearSelection() c.movePosition(QTextCursor.MoveOperation.PreviousCharacter, QTextCursor.MoveMode.KeepAnchor) - char = unicode_type(c.selectedText()).rstrip('\0') + char = str(c.selectedText()).rstrip('\0') return (c.blockNumber() + 1, col, char) def cut(self): @@ -509,7 +509,7 @@ def contextMenuEvent(self, ev): def fix_html(self): if self.syntax == 'html': from calibre.ebooks.oeb.polish.pretty import fix_html - self.editor.replace_text(fix_html(current_container(), unicode_type(self.editor.toPlainText())).decode('utf-8')) + self.editor.replace_text(fix_html(current_container(), str(self.editor.toPlainText())).decode('utf-8')) return True return False @@ -519,7 +519,7 @@ def pretty_print(self, name): ) if self.syntax in {'css', 'html', 'xml'}: func = {'css':pretty_css, 'xml':pretty_xml}.get(self.syntax, pretty_html) - original_text = unicode_type(self.editor.toPlainText()) + original_text = str(self.editor.toPlainText()) prettied_text = func(current_container(), name, original_text).decode('utf-8') if original_text != prettied_text: self.editor.replace_text(prettied_text) diff --git a/src/calibre/gui2/tweak_book/file_list.py b/src/calibre/gui2/tweak_book/file_list.py index e03359dae8..e69b7fc00e 100644 --- a/src/calibre/gui2/tweak_book/file_list.py +++ b/src/calibre/gui2/tweak_book/file_list.py @@ -40,7 +40,7 @@ from calibre.utils.icu import numeric_sort_key from calibre_extensions.progress_indicator import set_no_activate_on_click from polyglot.binary import as_hex_unicode -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems FILE_COPY_MIME = 'application/calibre-edit-book-files' @@ -107,14 +107,14 @@ def get_bulk_rename_settings(parent, number, msg=None, sanitize=sanitize_file_na ans = {'prefix': None, 'start': None} if d.exec_() == QDialog.DialogCode.Accepted: - prefix = sanitize(unicode_type(d.prefix.text())) + prefix = sanitize(str(d.prefix.text())) previous[category] = prefix tprefs.set('file-list-bulk-rename-prefix', previous) num = d.num.value() fmt = '%d' if leading_zeros: largest = num + number - 1 - fmt = '%0{0}d'.format(len(unicode_type(largest))) + fmt = '%0{0}d'.format(len(str(largest))) ans['prefix'] = prefix + fmt ans['start'] = num if allow_spine_order: @@ -128,7 +128,7 @@ class ItemDelegate(QStyledItemDelegate): # {{{ rename_requested = pyqtSignal(object, object) def setEditorData(self, editor, index): - name = unicode_type(index.data(NAME_ROLE) or '') + name = str(index.data(NAME_ROLE) or '') # We do this because Qt calls selectAll() unconditionally on the # editor, and we want only a part of the file name to be selected QTimer.singleShot(0, partial(self.set_editor_data, name, editor)) @@ -147,8 +147,8 @@ def set_editor_data(self, name, editor): editor.selectAll() def setModelData(self, editor, model, index): - newname = unicode_type(editor.text()) - oldname = unicode_type(index.data(NAME_ROLE) or '') + newname = str(editor.text()) + oldname = str(index.data(NAME_ROLE) or '') if newname != oldname: self.rename_requested.emit(oldname, newname) @@ -296,13 +296,13 @@ def mimeData(self, indices): def current_name(self): ci = self.currentItem() if ci is not None: - return unicode_type(ci.data(0, NAME_ROLE) or '') + return str(ci.data(0, NAME_ROLE) or '') return '' def get_state(self): s = {'pos':self.verticalScrollBar().value()} s['expanded'] = {c for c, item in iteritems(self.categories) if item.isExpanded()} - s['selected'] = {unicode_type(i.data(0, NAME_ROLE) or '') for i in self.selectedItems()} + s['selected'] = {str(i.data(0, NAME_ROLE) or '') for i in self.selectedItems()} return s def set_state(self, state): @@ -311,21 +311,21 @@ def set_state(self, state): self.verticalScrollBar().setValue(state['pos']) for parent in self.categories.values(): for c in (parent.child(i) for i in range(parent.childCount())): - name = unicode_type(c.data(0, NAME_ROLE) or '') + name = str(c.data(0, NAME_ROLE) or '') if name in state['selected']: c.setSelected(True) def item_from_name(self, name): for parent in self.categories.values(): for c in (parent.child(i) for i in range(parent.childCount())): - q = unicode_type(c.data(0, NAME_ROLE) or '') + q = str(c.data(0, NAME_ROLE) or '') if q == name: return c def select_name(self, name, set_as_current_index=False): for parent in self.categories.values(): for c in (parent.child(i) for i in range(parent.childCount())): - q = unicode_type(c.data(0, NAME_ROLE) or '') + q = str(c.data(0, NAME_ROLE) or '') c.setSelected(q == name) if q == name: self.scrollToItem(c) @@ -335,7 +335,7 @@ def select_name(self, name, set_as_current_index=False): def select_names(self, names, current_name=None): for parent in self.categories.values(): for c in (parent.child(i) for i in range(parent.childCount())): - q = unicode_type(c.data(0, NAME_ROLE) or '') + q = str(c.data(0, NAME_ROLE) or '') c.setSelected(q in names) if q == current_name: self.scrollToItem(c) @@ -592,9 +592,9 @@ def build_item_context_menu(self, item): container = current_container() ci = self.currentItem() if ci is not None: - cn = unicode_type(ci.data(0, NAME_ROLE) or '') - mt = unicode_type(ci.data(0, MIME_ROLE) or '') - cat = unicode_type(ci.data(0, CATEGORY_ROLE) or '') + cn = str(ci.data(0, NAME_ROLE) or '') + mt = str(ci.data(0, MIME_ROLE) or '') + cat = str(ci.data(0, CATEGORY_ROLE) or '') n = elided_text(cn.rpartition('/')[-1]) m.addAction(QIcon(I('save.png')), _('Export %s') % n, partial(self.export, cn)) if cn not in container.names_that_must_not_be_changed and cn not in container.names_that_must_not_be_removed and mt not in OEB_FONTS: @@ -630,7 +630,7 @@ def build_item_context_menu(self, item): selected_map = defaultdict(list) for item in sel: - selected_map[unicode_type(item.data(0, CATEGORY_ROLE) or '')].append(unicode_type(item.data(0, NAME_ROLE) or '')) + selected_map[str(item.data(0, CATEGORY_ROLE) or '')].append(str(item.data(0, NAME_ROLE) or '')) for items in selected_map.values(): items.sort(key=self.index_of_name) @@ -657,7 +657,7 @@ def index_of_name(self, name): for category, parent in iteritems(self.categories): for i in range(parent.childCount()): item = parent.child(i) - if unicode_type(item.data(0, NAME_ROLE) or '') == name: + if str(item.data(0, NAME_ROLE) or '') == name: return (category, i) return (None, -1) @@ -680,7 +680,7 @@ def mark_as_cover(self, name): self.mark_requested.emit(name, 'cover') def mark_as_titlepage(self, name): - first = unicode_type(self.categories['text'].child(0).data(0, NAME_ROLE) or '') == name + first = str(self.categories['text'].child(0).data(0, NAME_ROLE) or '') == name move_to_start = False if not first: move_to_start = question_dialog(self, _('Not first item'), _( @@ -706,7 +706,7 @@ def request_rename_common(self): ' internally. The filenames you see are automatically generated from the' ' internal structures of the original file.') % current_container().book_type.upper(), show=True) return - names = {unicode_type(item.data(0, NAME_ROLE) or '') for item in self.selectedItems()} + names = {str(item.data(0, NAME_ROLE) or '') for item in self.selectedItems()} bad = names & current_container().names_that_must_not_be_changed if bad: error_dialog(self, _('Cannot rename'), @@ -718,7 +718,7 @@ def request_rename_common(self): def request_bulk_rename(self): names = self.request_rename_common() if names is not None: - categories = Counter(unicode_type(item.data(0, CATEGORY_ROLE) or '') for item in self.selectedItems()) + categories = Counter(str(item.data(0, CATEGORY_ROLE) or '') for item in self.selectedItems()) settings = get_bulk_rename_settings(self, len(names), category=categories.most_common(1)[0][0], allow_spine_order=True) fmt, num = settings['prefix'], settings['start'] if fmt is not None: @@ -753,7 +753,7 @@ def change_name(name): @property def selected_names(self): - ans = {unicode_type(item.data(0, NAME_ROLE) or '') for item in self.selectedItems()} + ans = {str(item.data(0, NAME_ROLE) or '') for item in self.selectedItems()} ans.discard('') return ans @@ -772,9 +772,9 @@ def request_delete(self): text = self.categories['text'] children = (text.child(i) for i in range(text.childCount())) - spine_removals = [(unicode_type(item.data(0, NAME_ROLE) or ''), item.isSelected()) for item in children] - other_removals = {unicode_type(item.data(0, NAME_ROLE) or '') for item in self.selectedItems() - if unicode_type(item.data(0, CATEGORY_ROLE) or '') != 'text'} + spine_removals = [(str(item.data(0, NAME_ROLE) or ''), item.isSelected()) for item in children] + other_removals = {str(item.data(0, NAME_ROLE) or '') for item in self.selectedItems() + if str(item.data(0, CATEGORY_ROLE) or '') != 'text'} self.delete_requested.emit(spine_removals, other_removals) def delete_done(self, spine_removals, other_removals): @@ -786,7 +786,7 @@ def delete_done(self, spine_removals, other_removals): if category != 'text': for i in range(parent.childCount()): child = parent.child(i) - if unicode_type(child.data(0, NAME_ROLE) or '') in other_removals: + if str(child.data(0, NAME_ROLE) or '') in other_removals: removals.append(child) # The sorting by index is necessary otherwise Qt crashes with recursive @@ -823,7 +823,7 @@ def dropEvent(self, event): if current_order != pre_drop_order: order = [] for child in (text.child(i) for i in range(text.childCount())): - name = unicode_type(child.data(0, NAME_ROLE) or '') + name = str(child.data(0, NAME_ROLE) or '') linear = bool(child.data(0, LINEAR_ROLE)) order.append([name, linear]) # Ensure that all non-linear items are at the end, any non-linear @@ -834,14 +834,14 @@ def dropEvent(self, event): self.reorder_spine.emit(order) def item_double_clicked(self, item, column): - category = unicode_type(item.data(0, CATEGORY_ROLE) or '') + category = str(item.data(0, CATEGORY_ROLE) or '') if category: self._request_edit(item) def _request_edit(self, item): - category = unicode_type(item.data(0, CATEGORY_ROLE) or '') - mime = unicode_type(item.data(0, MIME_ROLE) or '') - name = unicode_type(item.data(0, NAME_ROLE) or '') + category = str(item.data(0, CATEGORY_ROLE) or '') + mime = str(item.data(0, MIME_ROLE) or '') + name = str(item.data(0, NAME_ROLE) or '') syntax = {'text':'html', 'styles':'css'}.get(category, None) self.edit_file.emit(name, syntax, mime) @@ -860,7 +860,7 @@ def edit_next_file(self, currently_editing=None, backwards=False): if backwards: items = reversed(tuple(items)) for item in items: - name = unicode_type(item.data(0, NAME_ROLE) or '') + name = str(item.data(0, NAME_ROLE) or '') if seen_current: self._request_edit(item) return True @@ -876,9 +876,9 @@ def all_files(self): def searchable_names(self): ans = {'text':OrderedDict(), 'styles':OrderedDict(), 'selected':OrderedDict(), 'open':OrderedDict()} for item in self.all_files: - category = unicode_type(item.data(0, CATEGORY_ROLE) or '') - mime = unicode_type(item.data(0, MIME_ROLE) or '') - name = unicode_type(item.data(0, NAME_ROLE) or '') + category = str(item.data(0, CATEGORY_ROLE) or '') + mime = str(item.data(0, MIME_ROLE) or '') + name = str(item.data(0, NAME_ROLE) or '') ok = category in {'text', 'styles'} if ok: ans[category][name] = syntax_from_mime(name, mime) @@ -938,7 +938,7 @@ def replace(self, name): def link_stylesheets(self, names): s = self.categories['styles'] - sheets = [unicode_type(s.child(i).data(0, NAME_ROLE) or '') for i in range(s.childCount())] + sheets = [str(s.child(i).data(0, NAME_ROLE) or '') for i in range(s.childCount())] if not sheets: return error_dialog(self, _('No stylesheets'), _( 'This book currently has no stylesheets. You must first create a stylesheet' @@ -971,7 +971,7 @@ def link_stylesheets(self, names): l.addWidget(bb) if d.exec_() == QDialog.DialogCode.Accepted: tprefs['remove_existing_links_when_linking_sheets'] = r.isChecked() - sheets = [unicode_type(s.item(il).text()) for il in range(s.count()) if s.item(il).checkState() == Qt.CheckState.Checked] + sheets = [str(s.item(il).text()) for il in range(s.count()) if s.item(il).checkState() == Qt.CheckState.Checked] if sheets: self.link_stylesheets_requested.emit(names, sheets, r.isChecked()) @@ -1037,7 +1037,7 @@ def do_import_file(self, path, hide_button=False): @property def name_is_ok(self): - return name_is_ok(unicode_type(self.name.text()), self.show_error) + return name_is_ok(str(self.name.text()), self.show_error) def update_ok(self, *args): self.ok_button.setEnabled(self.name_is_ok) @@ -1047,7 +1047,7 @@ def accept(self): return error_dialog(self, _('No name specified'), _( 'You must specify a name for the new file, with an extension, for example, chapter1.html'), show=True) tprefs['auto_link_stylesheets'] = self.link_css.isChecked() - name = unicode_type(self.name.text()) + name = str(self.name.text()) name, ext = name.rpartition('.')[0::2] name = (name + '.' + ext.lower()).replace('\\', '/') mt = guess_type(name) diff --git a/src/calibre/gui2/tweak_book/function_replace.py b/src/calibre/gui2/tweak_book/function_replace.py index ae5229ac18..7997ed892c 100644 --- a/src/calibre/gui2/tweak_book/function_replace.py +++ b/src/calibre/gui2/tweak_book/function_replace.py @@ -21,14 +21,14 @@ from calibre.utils.icu import capitalize, upper, lower, swapcase from calibre.utils.titlecase import titlecase from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.io import PolyglotStringIO user_functions = JSONConfig('editor-search-replace-functions') def compile_code(src, name=''): - if not isinstance(src, unicode_type): + if not isinstance(src, str): match = re.search(br'coding[:=]\s*([-\w.]+)', src[:200]) enc = match.group(1).decode('utf-8') if match else 'utf-8' src = src.decode(enc) diff --git a/src/calibre/gui2/tweak_book/manage_fonts.py b/src/calibre/gui2/tweak_book/manage_fonts.py index a962f00279..cfbdd201ae 100644 --- a/src/calibre/gui2/tweak_book/manage_fonts.py +++ b/src/calibre/gui2/tweak_book/manage_fonts.py @@ -21,7 +21,7 @@ from calibre.utils.icu import primary_sort_key as sort_key from calibre.utils.fonts.scanner import font_scanner, NoFonts from calibre.utils.fonts.metadata import FontMetadata, UnsupportedFont -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def rule_for_font(font_file, added_name): @@ -84,11 +84,11 @@ def populate_text(self): text.append('
  • ' + '' + face['path'] + '') name = face.get('full_name') or face.get('family_name') or face.get('subfamily_name') if name: - text.append('
    ' + _('Name:') + '\xa0' + unicode_type(name) + '') + text.append('
    ' + _('Name:') + '\xa0' + str(name) + '') if 'font-weight' in face: - text.append('
    ' + 'font-weight:\xa0' + unicode_type(face['font-weight'])) + text.append('
    ' + 'font-weight:\xa0' + str(face['font-weight'])) if 'font-style' in face: - text.append('
    ' + 'font-style:\xa0' + unicode_type(face['font-style'])) + text.append('
    ' + 'font-style:\xa0' + str(face['font-style'])) self.text.setHtml('\n'.join(text)) @@ -197,7 +197,7 @@ def setup_ui(self): @property def family(self): - return unicode_type(self._family.text()) + return str(self._family.text()) @property def normalized_family(self): diff --git a/src/calibre/gui2/tweak_book/plugin.py b/src/calibre/gui2/tweak_book/plugin.py index 07ab63dd31..d6841aa2ea 100644 --- a/src/calibre/gui2/tweak_book/plugin.py +++ b/src/calibre/gui2/tweak_book/plugin.py @@ -14,7 +14,7 @@ from calibre.customize.ui import all_edit_book_tool_plugins from calibre.gui2.tweak_book import current_container, tprefs from calibre.gui2.tweak_book.boss import get_boss -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues class Tool: @@ -81,7 +81,7 @@ def register_shortcut(self, qaction, unique_name, default_keys=(), short_text=No :param description: An optional longer description of this action, it will be used in the preferences entry for this shortcut. ''' - short_text = short_text or unicode_type(qaction.text()).replace('&&', '\0').replace('&', '').replace('\0', '&') + short_text = short_text or str(qaction.text()).replace('&&', '\0').replace('&', '').replace('\0', '&') self.gui.keyboard.register_shortcut( self.name + '_' + unique_name, short_text, default_keys=default_keys, action=qaction, description=description or '', group=_('Plugins')) diff --git a/src/calibre/gui2/tweak_book/preferences.py b/src/calibre/gui2/tweak_book/preferences.py index 33a52f83ba..921b267c58 100644 --- a/src/calibre/gui2/tweak_book/preferences.py +++ b/src/calibre/gui2/tweak_book/preferences.py @@ -9,7 +9,7 @@ from operator import attrgetter, methodcaller from functools import partial from collections import namedtuple -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from itertools import product from copy import copy, deepcopy @@ -77,7 +77,7 @@ def choices_widget(self, name, choices, fallback_val, none_val, prefs=None): widget.addItem(human or key, key) def getter(w): - ans = unicode_type(w.itemData(w.currentIndex()) or '') + ans = str(w.itemData(w.currentIndex()) or '') return {none_val:None}.get(ans, ans) def setter(w, val): @@ -104,7 +104,7 @@ def order_widget(self, name, prefs=None): widget.defaults = prefs.defaults[name] def getter(w): - return list(map(unicode_type, (w.item(i).text() for i in range(w.count())))) + return list(map(str, (w.item(i).text() for i in range(w.count())))) def setter(w, val): order_map = {x:i for i, x in enumerate(val)} @@ -353,7 +353,7 @@ def default_font(which): return s.fontFamily(which) def family_getter(which, w): - ans = unicode_type(w.currentFont().family()) + ans = str(w.currentFont().family()) if ans == default_font(which): ans = None return ans @@ -519,13 +519,13 @@ def read_settings(self, prefs=None): prefs = prefs or tprefs val = self.original_settings = {} for i in range(1, self.bars.count()): - name = unicode_type(self.bars.itemData(i) or '') + name = str(self.bars.itemData(i) or '') val[name] = copy(prefs[name]) self.current_settings = deepcopy(val) @property def current_name(self): - return unicode_type(self.bars.itemData(self.bars.currentIndex()) or '') + return str(self.bars.itemData(self.bars.currentIndex()) or '') def build_lists(self): from calibre.gui2.tweak_book.plugin import plugin_toolbar_actions @@ -549,12 +549,12 @@ def to_item(key, ac, parent): ic = ac.icon() if not ic or ic.isNull(): ic = blank - ans = QListWidgetItem(ic, unicode_type(ac.text()).replace('&', ''), parent) + ans = QListWidgetItem(ic, str(ac.text()).replace('&', ''), parent) ans.setData(Qt.ItemDataRole.UserRole, key) ans.setToolTip(ac.toolTip()) return ans - for key, ac in sorted(iteritems(all_items), key=lambda k_ac: unicode_type(k_ac[1].text())): + for key, ac in sorted(iteritems(all_items), key=lambda k_ac: str(k_ac[1].text())): if key not in applied: to_item(key, ac, self.available) if name == 'global_book_toolbar' and 'donate' not in applied: @@ -611,7 +611,7 @@ def _add_action(self, items): s = self.current_settings[self.current_name] except KeyError: return - names = [unicode_type(i.data(Qt.ItemDataRole.UserRole) or '') for i in items] + names = [str(i.data(Qt.ItemDataRole.UserRole) or '') for i in items] if not names: return for n in names: @@ -705,7 +705,7 @@ def setup_ui(self): @property def current_syntax(self): - return unicode_type(self.syntaxes.currentText()) + return str(self.syntaxes.currentText()) def show_template(self): from calibre.gui2.tweak_book.templates import raw_template_for @@ -723,7 +723,7 @@ def save_syntax(self): def _save_syntax(self): custom = tprefs['templates'] - custom[self.current_syntax] = unicode_type(self.editor.toPlainText()) + custom[self.current_syntax] = str(self.editor.toPlainText()) tprefs['templates'] = custom def restore_defaults(self): diff --git a/src/calibre/gui2/tweak_book/preview.py b/src/calibre/gui2/tweak_book/preview.py index 39ce779954..9433f071bc 100644 --- a/src/calibre/gui2/tweak_book/preview.py +++ b/src/calibre/gui2/tweak_book/preview.py @@ -39,7 +39,7 @@ ) from calibre.gui2.widgets2 import HistoryLineEdit2 from calibre.utils.ipc.simple_worker import offload_worker -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.queue import Empty, Queue from polyglot.urllib import urlparse @@ -195,7 +195,7 @@ def requestStarted(self, rq): QTimer.singleShot(0, self.check_for_parse) else: data = get_data(name) - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') mime_type = { # Prevent warning in console about mimetype of fonts @@ -461,7 +461,7 @@ def contextMenuEvent(self, ev): menu = QMenu(self) data = self._page.contextMenuData() url = data.linkUrl() - url = unicode_type(url.toString(NO_URL_FORMATTING)).strip() + url = str(url.toString(NO_URL_FORMATTING)).strip() text = data.selectedText() if text: ca = self.pageAction(QWebEnginePage.WebAction.Copy) @@ -590,7 +590,7 @@ def clear_clicked(self): self.view._page.findText('') def find(self, direction): - text = unicode_type(self.search.text()) + text = str(self.search.text()) self.view._page.findText(text, ( QWebEnginePage.FindFlag.FindBackward if direction == 'prev' else QWebEnginePage.FindFlags(0))) diff --git a/src/calibre/gui2/tweak_book/reports.py b/src/calibre/gui2/tweak_book/reports.py index 4fbbffafb6..39227b11be 100644 --- a/src/calibre/gui2/tweak_book/reports.py +++ b/src/calibre/gui2/tweak_book/reports.py @@ -36,7 +36,7 @@ from calibre.utils.icu import primary_contains, numeric_sort_key from calibre.utils.unicode_names import character_name_from_code from calibre.utils.localization import calibre_langcode_to_name, canonicalize_lang -from polyglot.builtins import iteritems, unicode_type, as_bytes +from polyglot.builtins import iteritems, as_bytes # Utils {{{ @@ -459,9 +459,9 @@ def data(self, index, role=Qt.ItemDataRole.DisplayRole): return entry.basename if col == 1: sz = entry.size / 1024. - return ('%.2f' % sz if int(sz) != sz else unicode_type(sz)) + return ('%.2f' % sz if int(sz) != sz else str(sz)) if col == 2: - return unicode_type(len(entry.usage)) + return str(len(entry.usage)) if col == 3: return '%d x %d' % (entry.width, entry.height) elif role == Qt.ItemDataRole.UserRole: @@ -732,7 +732,7 @@ def data(self, index, role=Qt.ItemDataRole.DisplayRole): ans += ' (%s)' % entry.locale.countrycode return ans if col == 2: - return unicode_type(len(entry.usage)) + return str(len(entry.usage)) elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] @@ -824,7 +824,7 @@ def data(self, index, role=Qt.ItemDataRole.DisplayRole): if col == 2: return ('U+%04X' if entry.codepoint < 0x10000 else 'U+%06X') % entry.codepoint if col == 3: - return unicode_type(entry.count) + return str(entry.count) elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] @@ -1005,7 +1005,7 @@ def __call__(self, data): self.rules = data['css'] self.num_unused = sum(1 for r in self.rules if r.count == 0) try: - self.num_size = len(unicode_type(max(r.count for r in self.rules))) + self.num_size = len(str(max(r.count for r in self.rules))) except ValueError: self.num_size = 1 self.build_maps() @@ -1229,7 +1229,7 @@ def __call__(self, data): self.rules = self.classes = tuple(data['classes']) self.num_unused = sum(1 for ce in self.classes if ce.num_of_matches == 0) try: - self.num_size = len(unicode_type(max(r.num_of_matches for r in self.classes))) + self.num_size = len(str(max(r.num_of_matches for r in self.classes))) except ValueError: self.num_size = 1 self.build_maps() diff --git a/src/calibre/gui2/tweak_book/search.py b/src/calibre/gui2/tweak_book/search.py index 75ccfda2a5..fe41480459 100644 --- a/src/calibre/gui2/tweak_book/search.py +++ b/src/calibre/gui2/tweak_book/search.py @@ -37,7 +37,7 @@ from calibre.gui2.tweak_book.widgets import BusyCursor from calibre.gui2.widgets2 import FlowLayout, HistoryComboBox from calibre.utils.icu import primary_contains -from polyglot.builtins import error_message, iteritems, unicode_type +from polyglot.builtins import error_message, iteritems # The search panel {{{ @@ -368,7 +368,7 @@ def mode(self, val): @property def find(self): - return unicode_type(self.find_text.text()) + return str(self.find_text.text()) @find.setter def find(self, val): @@ -378,7 +378,7 @@ def find(self, val): def replace(self): if self.mode == 'function': return self.functions.text() - return unicode_type(self.replace_text.text()) + return str(self.replace_text.text()) @replace.setter def replace(self, val): @@ -619,7 +619,7 @@ def data(self, index, role): return None def do_filter(self, text): - text = unicode_type(text) + text = str(text) self.beginResetModel() self.filtered_searches = [] for i, search in enumerate(self.searches): @@ -804,7 +804,7 @@ def abort_editing(self): @property def current_search(self): search = self.search.copy() - f = unicode_type(self.find.toPlainText()) + f = str(self.find.toPlainText()) search['find'] = f search['dot_all'] = bool(self.dot_all.isChecked()) search['case_sensitive'] = bool(self.case_sensitive.isChecked()) @@ -812,7 +812,7 @@ def current_search(self): if search['mode'] == 'function': r = self.function.text() else: - r = unicode_type(self.replace.toPlainText()) + r = str(self.replace.toPlainText()) search['replace'] = r return search @@ -831,7 +831,7 @@ def save_changes(self): search = self.search search['name'] = n - f = unicode_type(self.find.toPlainText()) + f = str(self.find.toPlainText()) if not f: error_dialog(self, _('Must specify find'), _( 'You must specify a find expression'), show=True) @@ -846,7 +846,7 @@ def save_changes(self): 'You must specify a function name in Function-Regex mode'), show=True) return False else: - r = unicode_type(self.replace.toPlainText()) + r = str(self.replace.toPlainText()) search['replace'] = r search['dot_all'] = bool(self.dot_all.isChecked()) diff --git a/src/calibre/gui2/tweak_book/spell.py b/src/calibre/gui2/tweak_book/spell.py index f2c738eee7..f4400bbab6 100644 --- a/src/calibre/gui2/tweak_book/spell.py +++ b/src/calibre/gui2/tweak_book/spell.py @@ -46,7 +46,7 @@ calibre_langcode_to_name, canonicalize_lang, get_lang, get_language ) from calibre_extensions.progress_indicator import set_no_activate_on_click -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems LANG = 0 COUNTRY = 1 @@ -117,7 +117,7 @@ def choose_file(self): @property def nickname(self): - return unicode_type(self.nick.text()).strip() + return str(self.nick.text()).strip() def accept(self): nick = self.nickname @@ -127,7 +127,7 @@ def accept(self): if nick in {d.name for d in custom_dictionaries()}: return error_dialog(self, _('Nickname already used'), _( 'A dictionary with the nick name "%s" already exists.') % nick, show=True) - oxt = unicode_type(self.path.text()) + oxt = str(self.path.text()) try: num = import_from_oxt(oxt, nick) except: @@ -253,7 +253,7 @@ def new_dictionary(self): name, ok = QInputDialog.getText(self, _('New dictionary'), _( 'Name of the new dictionary')) if ok: - name = unicode_type(name) + name = str(name) if name in {d.name for d in dictionaries.all_user_dictionaries}: return error_dialog(self, _('Already used'), _( 'A dictionary with the name %s already exists') % name, show=True) @@ -278,7 +278,7 @@ def rename_dictionary(self): name, ok = QInputDialog.getText(self, _('New name'), _( 'New name for the dictionary')) if ok: - name = unicode_type(name) + name = str(name) if name == d.name: return if name in {d.name for d in dictionaries.all_user_dictionaries}: @@ -334,7 +334,7 @@ def add_word(self): if d.exec_() != QDialog.DialogCode.Accepted: return d.loc.update_recently_used() - word = unicode_type(w.text()) + word = str(w.text()) lang = (loc.lang_codes or [canonicalize_lang(get_lang())])[0] if not word: return @@ -375,7 +375,7 @@ def import_words(self): if not lc: return error_dialog(self, _('Must specify language'), _( 'You must specify a language to import words'), show=True) - words = set(filter(None, [x.strip() for x in unicode_type(w.toPlainText()).splitlines()])) + words = set(filter(None, [x.strip() for x in str(w.toPlainText()).splitlines()])) lang = lc[0] words = {(w, lang) for w in words} - self.current_dictionary.words if dictionaries.add_to_user_dictionary(self.current_dictionary.name, words, DictionaryLocale(lang, None)): @@ -475,8 +475,8 @@ def manage_user_dictionaries(self): def data_changed(self, item, column): if column == 0 and item.type() == DICTIONARY: d = item.data(0, Qt.ItemDataRole.UserRole) - if not d.builtin and unicode_type(item.text(0)) != d.name: - rename_dictionary(d, unicode_type(item.text(0))) + if not d.builtin and str(item.text(0)) != d.name: + rename_dictionary(d, str(item.text(0))) def build_dictionaries(self, reread=False): all_dictionaries = builtin_dictionaries() | custom_dictionaries(reread=reread) @@ -559,7 +559,7 @@ def init_country(self, item): pc.setText((_( 'This is already the preferred variant for the {1} language') if preferred else _( 'Use this as the preferred variant for the {1} language')).format( - unicode_type(item.text(0)), unicode_type(item.parent().text(0)))) + str(item.text(0)), str(item.parent().text(0)))) pc.setEnabled(not preferred) def set_preferred_country(self): @@ -568,9 +568,9 @@ def set_preferred_country(self): bf.setBold(True) for x in (item.parent().child(i) for i in range(item.parent().childCount())): x.setData(0, Qt.ItemDataRole.FontRole, bf if x is item else None) - lc = unicode_type(item.parent().data(0, Qt.ItemDataRole.UserRole)) + lc = str(item.parent().data(0, Qt.ItemDataRole.UserRole)) pl = dprefs['preferred_locales'] - pl[lc] = '%s-%s' % (lc, unicode_type(item.data(0, Qt.ItemDataRole.UserRole))) + pl[lc] = '%s-%s' % (lc, str(item.data(0, Qt.ItemDataRole.UserRole))) dprefs['preferred_locales'] = pl def init_dictionary(self, item): @@ -589,8 +589,8 @@ def set_favorite(self): bf.setItalic(True) for x in (item.parent().child(i) for i in range(item.parent().childCount())): x.setData(0, Qt.ItemDataRole.FontRole, bf if x is item else None) - cc = unicode_type(item.parent().data(0, Qt.ItemDataRole.UserRole)) - lc = unicode_type(item.parent().parent().data(0, Qt.ItemDataRole.UserRole)) + cc = str(item.parent().data(0, Qt.ItemDataRole.UserRole)) + lc = str(item.parent().parent().data(0, Qt.ItemDataRole.UserRole)) d = item.data(0, Qt.ItemDataRole.UserRole) locale = '%s-%s' % (lc, cc) pl = dprefs['preferred_dictionaries'] @@ -997,7 +997,7 @@ def setup_ui(self): m.show_only_misspelt = hh.isSectionHidden(3) self.ignore_button = b = QPushButton(_('&Ignore')) - b.ign_text, b.unign_text = unicode_type(b.text()), _('Un&ignore') + b.ign_text, b.unign_text = str(b.text()), _('Un&ignore') b.ign_tt = _('Ignore the current word for the rest of this session') b.unign_tt = _('Stop ignoring the current word') b.clicked.connect(self.toggle_ignore) @@ -1006,7 +1006,7 @@ def setup_ui(self): h.setStretch(0, 1) l.addWidget(b), l.addSpacing(20) self.add_button = b = QPushButton(_('Add word to &dictionary:')) - b.add_text, b.remove_text = unicode_type(b.text()), _('Remove from &dictionaries') + b.add_text, b.remove_text = str(b.text()), _('Remove from &dictionaries') b.add_tt = _('Add the current word to the specified user dictionary') b.remove_tt = _('Remove the current word from all active user dictionaries') b.clicked.connect(self.add_remove) @@ -1071,7 +1071,7 @@ def sort_type_changed(self): def search_type_changed(self): tprefs['spell_check_case_sensitive_search'] = bool(self.case_sensitive_search.isChecked()) - if unicode_type(self.filter_text.text()).strip(): + if str(self.filter_text.text()).strip(): self.do_filter() def show_next_occurrence(self): @@ -1084,7 +1084,7 @@ def word_activated(self, index): self.find_word.emit(w, self.words_model.words[w]) def initialize_user_dictionaries(self): - ct = unicode_type(self.user_dictionaries.currentText()) + ct = str(self.user_dictionaries.currentText()) self.user_dictionaries.clear() self.user_dictionaries.addItems([d.name for d in dictionaries.active_user_dictionaries]) if ct: @@ -1159,7 +1159,7 @@ def change_word(self): w = self.words_model.word_for_row(row) if w is None: return - new_word = unicode_type(self.suggested_word.text()) + new_word = str(self.suggested_word.text()) self.change_requested.emit(w, new_word) def change_word_after_update(self, w, new_word): @@ -1215,7 +1215,7 @@ def add_remove(self): current = self.words_view.currentIndex() if current.isValid(): if self.user_dictionaries.isVisible(): # add - udname = unicode_type(self.user_dictionaries.currentText()) + udname = str(self.user_dictionaries.currentText()) self.words_model.add_word(current.row(), udname) else: self.words_model.remove_word(current.row()) @@ -1237,7 +1237,7 @@ def __exit__(self, *args): self.__current_word = None def do_filter(self): - text = unicode_type(self.filter_text.text()).strip() + text = str(self.filter_text.text()).strip() with self: self.words_model.filter(text) diff --git a/src/calibre/gui2/tweak_book/toc.py b/src/calibre/gui2/tweak_book/toc.py index 7984bb7120..5f724b8502 100644 --- a/src/calibre/gui2/tweak_book/toc.py +++ b/src/calibre/gui2/tweak_book/toc.py @@ -17,7 +17,6 @@ from calibre.gui2.toc.main import ItemEdit, TOCView from calibre.gui2.tweak_book import TOP, actions, current_container, tprefs from calibre_extensions.progress_indicator import set_no_activate_on_click -from polyglot.builtins import unicode_type class TOCEditor(QDialog): @@ -199,8 +198,8 @@ def iter_items(self, parent=None): def emit_navigate(self, *args): item = self.view.currentItem() if item is not None: - dest = unicode_type(item.data(0, DEST_ROLE) or '') - frag = unicode_type(item.data(0, FRAG_ROLE) or '') + dest = str(item.data(0, DEST_ROLE) or '') + frag = str(item.data(0, FRAG_ROLE) or '') if not frag: frag = TOP self.navigate_requested.emit(dest, frag) diff --git a/src/calibre/gui2/tweak_book/ui.py b/src/calibre/gui2/tweak_book/ui.py index de51050013..a94c5ee05d 100644 --- a/src/calibre/gui2/tweak_book/ui.py +++ b/src/calibre/gui2/tweak_book/ui.py @@ -52,7 +52,7 @@ localize_user_manual_link, localize_website_link ) from calibre.utils.unicode_names import character_name_from_code -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues def open_donate(): @@ -369,7 +369,7 @@ def __init__(self, opts, notify=None): self.cursor_position_widget = CursorPositionWidget(self) self.status_bar.addPermanentWidget(self.cursor_position_widget) self.status_bar_default_msg = la = QLabel(' ' + _('{0} {1} created by {2}').format(__appname__, get_version(), 'Kovid Goyal')) - la.base_template = unicode_type(la.text()) + la.base_template = str(la.text()) self.status_bar.addWidget(la) self.boss(self) @@ -414,10 +414,10 @@ def reg(icon, text, target, sid, keys, description, toolbar_allowed=False): toolbar_actions[sid] = ac if target is not None: ac.triggered.connect(target) - if isinstance(keys, unicode_type): + if isinstance(keys, str): keys = (keys,) self.keyboard.register_shortcut( - sid, unicode_type(ac.text()).replace('&', ''), default_keys=keys, description=description, action=ac, group=group) + sid, str(ac.text()).replace('&', ''), default_keys=keys, description=description, action=ac, group=group) self.addAction(ac) return ac @@ -718,7 +718,7 @@ def create_menubar(self): if self.plugin_menu_actions: e = b.addMenu(_('&Plugins')) - for ac in sorted(self.plugin_menu_actions, key=lambda x:sort_key(unicode_type(x.text()))): + for ac in sorted(self.plugin_menu_actions, key=lambda x:sort_key(str(x.text()))): e.addAction(ac) e = b.addMenu(_('&Help')) @@ -770,7 +770,7 @@ def add(bar, ac): bar.addAction(actions[ac]) except KeyError: if DEBUG: - prints('Unknown action for toolbar %r: %r' % (unicode_type(bar.objectName()), ac)) + prints('Unknown action for toolbar %r: %r' % (str(bar.objectName()), ac)) for x in tprefs['global_book_toolbar']: add(self.global_bar, x) diff --git a/src/calibre/gui2/tweak_book/widgets.py b/src/calibre/gui2/tweak_book/widgets.py index 78bac3b778..037a20e6d1 100644 --- a/src/calibre/gui2/tweak_book/widgets.py +++ b/src/calibre/gui2/tweak_book/widgets.py @@ -26,7 +26,7 @@ from calibre.utils.icu import primary_sort_key, sort_key, primary_contains, numeric_sort_key from calibre.utils.matcher import get_char, Matcher, DEFAULT_LEVEL1, DEFAULT_LEVEL2, DEFAULT_LEVEL3 from calibre.gui2.complete2 import EditWithComplete -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems ROOT = QModelIndex() @@ -69,7 +69,7 @@ def setup_ui(self): @property def tag(self): - return unicode_type(self.tag_input.text()).strip() + return str(self.tag_input.text()).strip() @classmethod def test(cls): @@ -130,7 +130,7 @@ def setup_ui(self): def folder_map(self): ans = {} for typ, x in self.TYPE_MAP: - val = unicode_type(getattr(self, '%s_folder' % typ).text()).strip().strip('/') + val = str(getattr(self, '%s_folder' % typ).text()).strip().strip('/') ans[typ] = val return ans @@ -242,15 +242,15 @@ def choose_destination(self): self.dest.setText(path) def accept(self): - if not unicode_type(self.src.text()): + if not str(self.src.text()): return error_dialog(self, _('Need document'), _( 'You must specify the source file that will be imported.'), show=True) Dialog.accept(self) @property def data(self): - src = unicode_type(self.src.text()).strip() - dest = unicode_type(self.dest.text()).strip() + src = str(self.src.text()).strip() + dest = str(self.dest.text()).strip() if not dest: dest = src.rpartition('.')[0] + '.epub' return src, dest @@ -457,7 +457,7 @@ def setup_ui(self): l.addWidget(self.bb, alignment=Qt.AlignmentFlag.AlignBottom) def update_matches(self, text): - text = unicode_type(text).strip() + text = str(text).strip() self.help_label.setVisible(False) self.results.setVisible(True) matches = self.matcher(text, limit=100) @@ -552,7 +552,7 @@ def data(self, index, role): return '\xa0' * 20 def filter(self, query): - query = unicode_type(query or '') + query = str(query or '') self.beginResetModel() if not query: self.items = tuple((text, None) for text in self.names) @@ -617,7 +617,7 @@ def set_names(self, names): self.filter('') def filter(self, query): - query = unicode_type(query or '') + query = str(query or '') self.beginResetModel() self.items = [x for x in self.names if primary_contains(query, x[0]) or primary_contains(query, x[1])] self.endResetModel() @@ -745,11 +745,11 @@ def update_target(self): @property def href(self): - return unicode_type(self.target.text()).strip() + return str(self.target.text()).strip() @property def text(self): - return unicode_type(self.text_edit.text()).strip() + return str(self.text_edit.text()).strip() @property def template(self): @@ -889,7 +889,7 @@ def help_requested(self): d.exec_() def semantic_type_changed(self): - item_type = unicode_type(self.semantic_type.itemData(self.semantic_type.currentIndex()) or '') + item_type = str(self.semantic_type.itemData(self.semantic_type.currentIndex()) or '') name, frag = self.final_type_map.get(item_type, (None, None)) self.show_type(name, frag) @@ -914,8 +914,8 @@ def show_type(self, name, frag): self.target.blockSignals(False) def target_text_changed(self): - name, frag = unicode_type(self.target.text()).partition('#')[::2] - item_type = unicode_type(self.semantic_type.itemData(self.semantic_type.currentIndex()) or '') + name, frag = str(self.target.text()).partition('#')[::2] + item_type = str(self.semantic_type.itemData(self.semantic_type.currentIndex()) or '') self.final_type_map[item_type] = (name, frag or None) def selected_file_changed(self, *args): @@ -1033,7 +1033,7 @@ def filtered_properties(self): a('float'), a('clear') if self.opt_colors.isChecked(): a('color'), a('background-color') - for x in unicode_type(self.others.text()).split(','): + for x in str(self.others.text()).split(','): x = x.strip() if x: a(x) @@ -1209,7 +1209,7 @@ def toPlainText(self): return to_plain_text(self) def selected_text_from_cursor(self, cursor): - return unicodedata.normalize('NFC', unicode_type(cursor.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0')) + return unicodedata.normalize('NFC', str(cursor.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0')) @property def selected_text(self): diff --git a/src/calibre/gui2/ui.py b/src/calibre/gui2/ui.py index 255369b964..a7f0aad624 100644 --- a/src/calibre/gui2/ui.py +++ b/src/calibre/gui2/ui.py @@ -60,7 +60,7 @@ from calibre.srv.library_broker import GuiLibraryBroker, db_matches from calibre.utils.config import dynamic, prefs from calibre.utils.ipc.pool import Pool -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes from polyglot.queue import Empty, Queue @@ -606,7 +606,7 @@ def test_server(self, *args): if self.content_server is not None and \ self.content_server.exception is not None: error_dialog(self, _('Failed to start Content server'), - unicode_type(self.content_server.exception)).exec_() + str(self.content_server.exception)).exec_() @property def current_db(self): @@ -1043,7 +1043,7 @@ def job_exception(self, job, dialog_title=_('Conversion error'), retry_func=None pass if not minz: self.job_error_dialog.show_error(dialog_title, - _('Failed')+': '+unicode_type(job.description), + _('Failed')+': '+str(job.description), det_msg=job.details, retry_func=retry_func) def read_settings(self): diff --git a/src/calibre/gui2/update.py b/src/calibre/gui2/update.py index 3308dde971..b673f25508 100644 --- a/src/calibre/gui2/update.py +++ b/src/calibre/gui2/update.py @@ -19,7 +19,6 @@ from calibre.gui2.dialogs.plugin_updater import get_plugin_updates_available from calibre.utils.serialize import msgpack_dumps, msgpack_loads from polyglot.binary import as_hex_unicode, from_hex_bytes -from polyglot.builtins import unicode_type URL = 'https://code.calibre-ebook.com/latest' # URL = 'http://localhost:8000/latest' @@ -60,7 +59,7 @@ def get_newest_version(): except UnicodeDecodeError: version = '' ans = NO_CALIBRE_UPDATE - m = re.match(unicode_type(r'(\d+)\.(\d+).(\d+)$'), version) + m = re.match(r'(\d+)\.(\d+).(\d+)$', version) if m is not None: ans = tuple(map(int, (m.group(1), m.group(2), m.group(3)))) return ans @@ -213,7 +212,7 @@ def update_found(self, calibre_version, number_of_plugin_updates, force=False, n has_plugin_updates = number_of_plugin_updates > 0 self.plugin_update_found(number_of_plugin_updates) version_url = as_hex_unicode(msgpack_dumps((calibre_version, number_of_plugin_updates))) - calibre_version = '.'.join(map(unicode_type, calibre_version)) + calibre_version = '.'.join(map(str, calibre_version)) if not has_calibre_update and not has_plugin_updates: self.status_bar.update_label.setVisible(False) @@ -264,7 +263,7 @@ def plugin_update_found(self, number_of_updates): plugin.qaction.setToolTip(_('Install and configure user plugins')) def update_link_clicked(self, url): - url = unicode_type(url) + url = str(url) if url.startswith('update:'): calibre_version, number_of_plugin_updates = msgpack_loads(from_hex_bytes(url[len('update:'):])) self.update_found(calibre_version, number_of_plugin_updates, force=True) diff --git a/src/calibre/gui2/viewer/bookmarks.py b/src/calibre/gui2/viewer/bookmarks.py index 017f2123da..13529f63d3 100644 --- a/src/calibre/gui2/viewer/bookmarks.py +++ b/src/calibre/gui2/viewer/bookmarks.py @@ -17,7 +17,6 @@ from calibre.gui2.viewer.web_view import vprefs from calibre.utils.date import EPOCH, utcnow from calibre.utils.icu import primary_sort_key -from polyglot.builtins import unicode_type class BookmarksList(QListWidget): @@ -241,7 +240,7 @@ def uniqify_bookmark_title(self, base): def item_changed(self, item): self.bookmarks_list.blockSignals(True) - title = unicode_type(item.data(Qt.ItemDataRole.DisplayRole)) or _('Unknown') + title = str(item.data(Qt.ItemDataRole.DisplayRole)) or _('Unknown') title = self.uniqify_bookmark_title(title) item.setData(Qt.ItemDataRole.DisplayRole, title) item.setData(Qt.ItemDataRole.ToolTipRole, title) @@ -352,7 +351,7 @@ def create_new_bookmark(self, pos_data): title, ok = QInputDialog.getText(self, _('Add bookmark'), _('Enter title for bookmark:'), text=pos_data.get('selected_text') or default_title) - title = unicode_type(title).strip() + title = str(title).strip() if not ok or not title: return title = self.uniqify_bookmark_title(title) diff --git a/src/calibre/gui2/viewer/search.py b/src/calibre/gui2/viewer/search.py index f1263e3c1f..0a449da0f5 100644 --- a/src/calibre/gui2/viewer/search.py +++ b/src/calibre/gui2/viewer/search.py @@ -18,7 +18,7 @@ from calibre.gui2.viewer.config import vprefs from calibre.gui2.viewer.web_view import get_data, get_manifest from calibre.gui2.viewer.widgets import ResultsDelegate, SearchBox -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.functools import lru_cache from polyglot.queue import Queue @@ -178,7 +178,7 @@ def searchable_text_for_name(name): anchor_offset_map = OrderedDict() while stack: node = stack.pop() - if isinstance(node, unicode_type): + if isinstance(node, str): ans.append(node) text_pos += len(node) continue diff --git a/src/calibre/gui2/viewer/web_view.py b/src/calibre/gui2/viewer/web_view.py index 7eb9953bf9..2f6e741376 100644 --- a/src/calibre/gui2/viewer/web_view.py +++ b/src/calibre/gui2/viewer/web_view.py @@ -38,7 +38,7 @@ from calibre.srv.code import get_translations_data from calibre.utils.serialize import json_loads from calibre.utils.shared_file import share_open -from polyglot.builtins import as_bytes, iteritems, unicode_type +from polyglot.builtins import as_bytes, iteritems from polyglot.functools import lru_cache SANDBOX_HOST = FAKE_HOST.rpartition('.')[0] + '.sandbox' @@ -681,7 +681,7 @@ def set_local_storage(self, key, val): vprefs['local_storage'] = sd def do_callback(self, func_name, callback): - cid = unicode_type(next(self.callback_id_counter)) + cid = str(next(self.callback_id_counter)) self.callback_map[cid] = callback self.execute_when_ready('get_current_cfi', cid) diff --git a/src/calibre/gui2/webengine.py b/src/calibre/gui2/webengine.py index b55c8b62e2..9ae40ba56e 100644 --- a/src/calibre/gui2/webengine.py +++ b/src/calibre/gui2/webengine.py @@ -11,7 +11,7 @@ from calibre import prints from calibre.utils.monotonic import monotonic from calibre.utils.rapydscript import special_title -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def secure_webengine(view_or_page_or_settings, for_viewer=False): @@ -60,7 +60,7 @@ def create_script( from_js = pyqtSignal -class to_js(unicode_type): +class to_js(str): def __call__(self, *a): prints('WARNING: Calling {}() before the javascript bridge is ready'.format(self.name)) diff --git a/src/calibre/gui2/widgets.py b/src/calibre/gui2/widgets.py index 9dc39e1119..26076f1595 100644 --- a/src/calibre/gui2/widgets.py +++ b/src/calibre/gui2/widgets.py @@ -25,7 +25,7 @@ from calibre.gui2.dnd import (dnd_has_image, dnd_get_image, dnd_get_files, image_extensions, dnd_has_extension, dnd_get_local_image_and_pixmap, DownloadDialog) from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import native_string_type, unicode_type +from polyglot.builtins import native_string_type history = XMLConfig('history') @@ -86,7 +86,7 @@ def initialize(self, defaults=False): # Get all items in the combobox. If we are resetting # to defaults we don't want to lose what the user # has added. - val_hist = [unicode_type(self.re.lineEdit().text())] + [unicode_type(self.re.itemText(i)) for i in range(self.re.count())] + val_hist = [str(self.re.lineEdit().text())] + [str(self.re.itemText(i)) for i in range(self.re.count())] self.re.clear() if defaults: @@ -109,7 +109,7 @@ def initialize(self, defaults=False): def do_test(self): from calibre.ebooks.metadata import authors_to_string from calibre.ebooks.metadata.meta import metadata_from_filename - fname = unicode_type(self.filename.text()) + fname = str(self.filename.text()) ext = os.path.splitext(fname)[1][1:].lower() if ext not in BOOK_EXTENSIONS: return warning_dialog(self, _('Test file name invalid'), @@ -139,7 +139,7 @@ def do_test(self): self.series.setText(_('No match')) if mi.series_index is not None: - self.series_index.setText(unicode_type(mi.series_index)) + self.series_index.setText(str(mi.series_index)) else: self.series_index.setText(_('No match')) @@ -153,11 +153,11 @@ def do_test(self): else: self.pubdate.setText(_('No match')) - self.isbn.setText(_('No match') if mi.isbn is None else unicode_type(mi.isbn)) + self.isbn.setText(_('No match') if mi.isbn is None else str(mi.isbn)) self.comments.setText(mi.comments if mi.comments else _('No match')) def pattern(self): - pat = unicode_type(self.re.lineEdit().text()) + pat = str(self.re.lineEdit().text()) return re.compile(pat) def commit(self): @@ -165,7 +165,7 @@ def commit(self): prefs['filename_pattern'] = pat history = [] - history_pats = [unicode_type(self.re.lineEdit().text())] + [unicode_type(self.re.itemText(i)) for i in range(self.re.count())] + history_pats = [str(self.re.lineEdit().text())] + [str(self.re.itemText(i)) for i in range(self.re.count())] for p in history_pats[:24]: # Ensure we don't have duplicate items. if p and p not in history: @@ -496,23 +496,23 @@ def contextMenuEvent(self, event): def upper_case(self): from calibre.utils.icu import upper - self.setText(upper(unicode_type(self.text()))) + self.setText(upper(str(self.text()))) def lower_case(self): from calibre.utils.icu import lower - self.setText(lower(unicode_type(self.text()))) + self.setText(lower(str(self.text()))) def swap_case(self): from calibre.utils.icu import swapcase - self.setText(swapcase(unicode_type(self.text()))) + self.setText(swapcase(str(self.text()))) def title_case(self): from calibre.utils.titlecase import titlecase - self.setText(titlecase(unicode_type(self.text()))) + self.setText(titlecase(str(self.text()))) def capitalize(self): from calibre.utils.icu import capitalize - self.setText(capitalize(unicode_type(self.text()))) + self.setText(capitalize(str(self.text()))) # }}} @@ -595,13 +595,13 @@ def set_space_before_sep(self, space_before): self.space_before_sep = space_before def text_changed(self, text): - all_text = unicode_type(text) + all_text = str(text) text = all_text[:self.cursorPosition()] prefix = text.split(self.separator)[-1].strip() text_items = [] for t in all_text.split(self.separator): - t1 = unicode_type(t).strip() + t1 = str(t).strip() if t1: text_items.append(t) text_items = list(set(text_items)) @@ -609,8 +609,8 @@ def text_changed(self, text): def complete_text(self, text): cursor_pos = self.cursorPosition() - before_text = unicode_type(self.text())[:cursor_pos] - after_text = unicode_type(self.text())[cursor_pos:] + before_text = str(self.text())[:cursor_pos] + after_text = str(self.text())[cursor_pos:] prefix_len = len(before_text.split(self.separator)[-1].lstrip()) if self.space_before_sep: complete_text_pat = '%s%s %s %s' @@ -639,7 +639,7 @@ def __init__(self, *args): self.setMinimumContentsLength(20) def text(self): - return unicode_type(self.currentText()) + return str(self.currentText()) def setText(self, text): idx = self.findText(text, Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive) @@ -696,11 +696,11 @@ def initialize(self, name): def save_history(self): items = [] - ct = unicode_type(self.currentText()) + ct = str(self.currentText()) if ct: items.append(ct) for i in range(self.count()): - item = unicode_type(self.itemText(i)) + item = str(self.itemText(i)) if item not in items: items.append(item) self.blockSignals(True) @@ -1098,7 +1098,7 @@ def __init__(self, name, label, icon, initial_show=True, parent.addAction(self.action_toggle) if hasattr(parent, 'keyboard'): parent.keyboard.register_shortcut('splitter %s %s'%(name, - label), unicode_type(self.action_toggle.text()), + label), str(self.action_toggle.text()), default_keys=(shortcut,), action=self.action_toggle) else: self.action_toggle.setShortcut(shortcut) diff --git a/src/calibre/gui2/widgets2.py b/src/calibre/gui2/widgets2.py index a8b81b8ed3..d56c25d3b2 100644 --- a/src/calibre/gui2/widgets2.py +++ b/src/calibre/gui2/widgets2.py @@ -19,7 +19,6 @@ from calibre.gui2.widgets import history from calibre.utils.config_base import tweaks from calibre.utils.date import UNDEFINED_DATE -from polyglot.builtins import unicode_type from polyglot.functools import lru_cache @@ -50,7 +49,7 @@ def load_history(self): return history.get(self.store_name, []) def save_history(self): - ct = unicode_type(self.text()) + ct = str(self.text()) if len(ct) >= self.min_history_entry_length: try: self.history.remove(ct) @@ -104,7 +103,7 @@ def color(self): @color.setter def color(self, val): - val = unicode_type(val or '') + val = str(val or '') col = QColor(val) orig = self._color if col.isValid(): @@ -123,7 +122,7 @@ def color(self, val): def choose_color(self): col = QColorDialog.getColor(QColor(self._color or Qt.GlobalColor.white), self, _('Choose a color')) if col.isValid(): - self.color = unicode_type(col.name()) + self.color = str(col.name()) def access_key(k): diff --git a/src/calibre/gui2/win_file_dialogs.py b/src/calibre/gui2/win_file_dialogs.py index 6fc619aabe..5406761a3a 100644 --- a/src/calibre/gui2/win_file_dialogs.py +++ b/src/calibre/gui2/win_file_dialogs.py @@ -12,7 +12,7 @@ from contextlib import suppress -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes is64bit = sys.maxsize > (1 << 32) base = sys.extensions_location if hasattr(sys, 'new_app_layout') else os.path.dirname(sys.executable) @@ -61,7 +61,7 @@ def serialize_binary(key, val): def serialize_string(key, val): key = key.encode('ascii') if not isinstance(key, bytes) else key - val = unicode_type(val).encode('utf-8') + val = str(val).encode('utf-8') if len(val) > 2**16 - 1: raise ValueError('%s is too long' % key) return struct.pack('=B%dsH%ds' % (len(key), len(val)), len(key), key, len(val), val) @@ -205,7 +205,7 @@ def get_errors(): from calibre import prints from calibre.constants import DEBUG if DEBUG: - prints('stdout+stderr from file dialog helper:', unicode_type([h.stdoutdata, h.stderrdata])) + prints('stdout+stderr from file dialog helper:', str([h.stdoutdata, h.stderrdata])) if h.rc != 0: raise Exception('File dialog failed (return code %s): %s' % (h.rc, get_errors())) @@ -218,7 +218,7 @@ def get_errors(): return () parts = list(filter(None, server.data.split(b'\0'))) if DEBUG: - prints('piped data from file dialog helper:', unicode_type(parts)) + prints('piped data from file dialog helper:', str(parts)) if len(parts) < 2: return () if parts[0] != secret: diff --git a/src/calibre/gui2/wizard/__init__.py b/src/calibre/gui2/wizard/__init__.py index a0a4738706..9ca7af1a38 100644 --- a/src/calibre/gui2/wizard/__init__.py +++ b/src/calibre/gui2/wizard/__init__.py @@ -26,7 +26,7 @@ from calibre.gui2.wizard.stanza_ui import Ui_WizardPage as StanzaUI from calibre.utils.config import dynamic, prefs from calibre.utils.localization import localize_user_manual_link -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems # Devices {{{ @@ -537,14 +537,14 @@ def initializePage(self): self.to_address.setText(accs[0][0]) def x(): - t = unicode_type(self.to_address.text()) + t = str(self.to_address.text()) if t.strip(): return t.strip() self.send_email_widget.initialize(x) def commit(self): - x = unicode_type(self.to_address.text()).strip() + x = str(self.to_address.text()).strip() parts = x.split('@') if (len(parts) >= 2 and parts[0] and self.send_email_widget.set_email_settings(True)): @@ -605,8 +605,8 @@ def set_port(self, *args): for p in range(8080, 8100): try: s.bind(('0.0.0.0', p)) - t = unicode_type(self.instructions.text()) - t = re.sub(r':\d+', ':'+unicode_type(p), t) + t = str(self.instructions.text()) + t = re.sub(r':\d+', ':'+str(p), t) self.instructions.setText(t) return p except: @@ -733,10 +733,10 @@ def get_esc_lang(l): for item in items: self.language.addItem(item[1], (item[0])) self.language.blockSignals(False) - prefs['language'] = unicode_type(self.language.itemData(self.language.currentIndex()) or '') + prefs['language'] = str(self.language.itemData(self.language.currentIndex()) or '') def change_language(self, idx): - prefs['language'] = unicode_type(self.language.itemData(self.language.currentIndex()) or '') + prefs['language'] = str(self.language.itemData(self.language.currentIndex()) or '') from polyglot.builtins import builtins builtins.__dict__['_'] = lambda x: x from calibre.ebooks.metadata.book.base import reset_field_metadata @@ -774,7 +774,7 @@ def is_library_dir_suitable(self, x): return False def validatePage(self): - newloc = unicode_type(self.location.text()) + newloc = str(self.location.text()) if not self.is_library_dir_suitable(newloc): self.show_library_dir_error(newloc) return False @@ -804,11 +804,11 @@ def change(self): self.show_library_dir_error(x) def show_library_dir_error(self, x): - if not isinstance(x, unicode_type): + if not isinstance(x, str): try: x = x.decode(filesystem_encoding) except: - x = unicode_type(repr(x)) + x = str(repr(x)) error_dialog(self, _('Bad location'), _('You must choose an empty folder for ' 'the calibre library. %s is not empty.')%x, show=True) @@ -846,7 +846,7 @@ def initializePage(self): def isComplete(self): try: - lp = unicode_type(self.location.text()) + lp = str(self.location.text()) ans = bool(lp) and os.path.exists(lp) and os.path.isdir(lp) and os.access(lp, os.W_OK) except: @@ -854,7 +854,7 @@ def isComplete(self): return ans def commit(self): - newloc = unicode_type(self.location.text()) + newloc = str(self.location.text()) try: dln = self.default_library_name if (dln and os.path.exists(dln) and not os.listdir(dln) and newloc != dln): @@ -949,8 +949,8 @@ def accept(self): QWizard.accept(self) def set_finish_text(self, *args): - bt = unicode_type("" + self.buttonText(QWizard.WizardButton.FinishButton) + "").replace('&', '') - t = unicode_type(self.finish_page.finish_text.text()) + bt = str("" + self.buttonText(QWizard.WizardButton.FinishButton) + "").replace('&', '') + t = str(self.finish_page.finish_text.text()) if '%s' in t: self.finish_page.finish_text.setText(t%bt) diff --git a/src/calibre/gui2/wizard/send_email.py b/src/calibre/gui2/wizard/send_email.py index 9ea2f0c60e..131a46db3d 100644 --- a/src/calibre/gui2/wizard/send_email.py +++ b/src/calibre/gui2/wizard/send_email.py @@ -19,7 +19,6 @@ from calibre.gui2.wizard.send_email_ui import Ui_Form from calibre.utils.smtp import config as smtp_prefs from calibre.gui2 import error_dialog, question_dialog -from polyglot.builtins import unicode_type from polyglot.binary import as_hex_unicode, from_hex_unicode from polyglot.io import PolyglotStringIO @@ -70,7 +69,7 @@ def start_test(self, *args): def run_test(self): try: - tb = self.test_func(unicode_type(self.to.text())) or _('Email successfully sent') + tb = self.test_func(str(self.to.text())) or _('Email successfully sent') except Exception: import traceback tb = traceback.format_exc() @@ -132,7 +131,7 @@ def __init__(self, service, parent): self.service = service def accept(self): - un = unicode_type(self.username.text()) + un = str(self.username.text()) if self.service.get('at_in_username', False) and '@' not in un: return error_dialog(self, _('Incorrect username'), _('%s needs the full email address as your username') % @@ -267,14 +266,14 @@ def create_service_relay(self, service, *args): self.relay_tls.setChecked(True) def set_email_settings(self, to_set): - from_ = unicode_type(self.email_from.text()).strip() + from_ = str(self.email_from.text()).strip() if to_set and not from_: error_dialog(self, _('Bad configuration'), _('You must set the From email address')).exec_() return False - username = unicode_type(self.relay_username.text()).strip() - password = unicode_type(self.relay_password.text()).strip() - host = unicode_type(self.relay_host.text()).strip() + username = str(self.relay_username.text()).strip() + password = str(self.relay_password.text()).strip() + host = str(self.relay_host.text()).strip() enc_method = ('TLS' if self.relay_tls.isChecked() else 'SSL' if self.relay_ssl.isChecked() else 'NONE') if host: diff --git a/src/calibre/library/caches.py b/src/calibre/library/caches.py index 43db8ae9da..c191a71426 100644 --- a/src/calibre/library/caches.py +++ b/src/calibre/library/caches.py @@ -20,7 +20,7 @@ from calibre.ebooks.metadata import title_sort, author_to_author_sort from calibre.ebooks.metadata.opf2 import metadata_to_opf from calibre import prints, force_unicode -from polyglot.builtins import iteritems, itervalues, unicode_type, string_or_bytes, cmp +from polyglot.builtins import iteritems, itervalues, string_or_bytes, cmp class MetadataBackup(Thread): # {{{ @@ -137,7 +137,7 @@ def set_use_primary_find_in_search(toWhat): def force_to_bool(val): - if isinstance(val, (bytes, unicode_type)): + if isinstance(val, (bytes, str)): if isinstance(val, bytes): val = force_unicode(val) try: @@ -359,7 +359,7 @@ def get_dates_matches(self, location, query, candidates): if item is None: continue v = item[loc] - if isinstance(v, (bytes, unicode_type)): + if isinstance(v, (bytes, str)): v = parse_date(v) if v is None or v <= UNDEFINED_DATE: matches.add(item[0]) @@ -370,7 +370,7 @@ def get_dates_matches(self, location, query, candidates): if item is None: continue v = item[loc] - if isinstance(v, (bytes, unicode_type)): + if isinstance(v, (bytes, str)): v = parse_date(v) if v is not None and v > UNDEFINED_DATE: matches.add(item[0]) @@ -414,7 +414,7 @@ def get_dates_matches(self, location, query, candidates): if item is None or item[loc] is None: continue v = item[loc] - if isinstance(v, (bytes, unicode_type)): + if isinstance(v, (bytes, str)): v = parse_date(v) if relop(v, qd, field_count): matches.add(item[0]) @@ -741,7 +741,7 @@ def get_matches(self, location, query, candidates=None, # everything else, or 'all' matches matchkind, query = self._matchkind(query) - if not isinstance(query, unicode_type): + if not isinstance(query, str): query = query.decode('utf-8') db_col = {} @@ -926,7 +926,7 @@ def set_marked_ids(self, id_dict): self.marked_ids_dict = dict.fromkeys(id_dict, 'true') else: # Ensure that all the items in the dict are text - self.marked_ids_dict = dict(zip(iter(id_dict), map(unicode_type, + self.marked_ids_dict = dict(zip(iter(id_dict), map(str, itervalues(id_dict)))) # Set the values in the cache diff --git a/src/calibre/library/catalogs/bibtex.py b/src/calibre/library/catalogs/bibtex.py index ae572e6607..885bfa783a 100644 --- a/src/calibre/library/catalogs/bibtex.py +++ b/src/calibre/library/catalogs/bibtex.py @@ -14,7 +14,7 @@ from calibre.library.catalogs import FIELDS, TEMPLATE_ALLOWED_FIELDS from calibre.customize.conversion import DummyReporter from calibre.ebooks.metadata import format_isbn -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes class BIBTEX(CatalogPlugin): @@ -248,7 +248,7 @@ def tpl_replace(objtplname) : elif tpl_field in ['tags', 'authors'] : tpl_field =entry[tpl_field][0] elif tpl_field in ['id', 'series_index'] : - tpl_field = unicode_type(entry[tpl_field]) + tpl_field = str(entry[tpl_field]) else : tpl_field = entry[tpl_field] return ascii_text(tpl_field) @@ -267,7 +267,7 @@ def tpl_replace(objtplname) : template_citation = '%s' % re.sub(r'[\D]','', entry["isbn"]) else : - template_citation = '%s' % unicode_type(entry["id"]) + template_citation = '%s' % str(entry["id"]) return bibtexclass.ValidateCitationKey(template_citation) diff --git a/src/calibre/library/catalogs/csv_xml.py b/src/calibre/library/catalogs/csv_xml.py index e7fa53df53..4abec9afcd 100644 --- a/src/calibre/library/catalogs/csv_xml.py +++ b/src/calibre/library/catalogs/csv_xml.py @@ -12,7 +12,6 @@ from calibre.customize import CatalogPlugin from calibre.library.catalogs import FIELDS from calibre.customize.conversion import DummyReporter -from polyglot.builtins import unicode_type class CSV_XML(CatalogPlugin): @@ -155,14 +154,14 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): item = '%.2g' % (item / 2) # Convert HTML to markdown text - if isinstance(item, unicode_type): + if isinstance(item, str): opening_tag = re.search(r'<(\w+)( |>)', item) if opening_tag: closing_tag = re.search(r'<\/%s>$' % opening_tag.group(1), item) if closing_tag: item = html2text(item) - outstr.append('"%s"' % unicode_type(item).replace('"', '""')) + outstr.append('"%s"' % str(item).replace('"', '""')) outfile.write(','.join(outstr) + '\n') outfile.close() @@ -181,8 +180,8 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): for field in fields: if field.startswith('#'): val = db.get_field(r['id'], field, index_is_id=True) - if not isinstance(val, unicode_type): - val = unicode_type(val) + if not isinstance(val, str): + val = str(val) item = getattr(E, field.replace('#', '_'))(val) record.append(item) @@ -192,11 +191,11 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): val = r[field] if not val: continue - if not isinstance(val, (bytes, unicode_type)): + if not isinstance(val, (bytes, str)): if (fm.get(field, {}).get('datatype', None) == 'rating' and val): val = '%.2g' % (val / 2) - val = unicode_type(val) + val = str(val) item = getattr(E, field)(val) record.append(item) @@ -225,7 +224,7 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): if 'series' in fields and r['series']: record.append(E.series(r['series'], - index=unicode_type(r['series_index']))) + index=str(r['series_index']))) if 'languages' in fields and r['languages']: record.append(E.languages(r['languages'])) diff --git a/src/calibre/library/catalogs/epub_mobi.py b/src/calibre/library/catalogs/epub_mobi.py index ff259eac4a..ea94a41227 100644 --- a/src/calibre/library/catalogs/epub_mobi.py +++ b/src/calibre/library/catalogs/epub_mobi.py @@ -16,7 +16,6 @@ from calibre.library.catalogs import AuthorSortMismatchException, EmptyCatalogException from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.localization import calibre_langcode_to_name, canonicalize_lang, get_lang -from polyglot.builtins import unicode_type Option = namedtuple('Option', 'option, default, dest, action, help') @@ -398,7 +397,7 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): if opts.verbose: log.info(" Begin catalog source generation (%s)" % - unicode_type(datetime.timedelta(seconds=int(time.time() - opts.start_time)))) + str(datetime.timedelta(seconds=int(time.time() - opts.start_time)))) # Launch the Catalog builder catalog = CatalogBuilder(db, opts, self, report_progress=notification) @@ -407,7 +406,7 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): catalog.build_sources() if opts.verbose: log.info(" Completed catalog source generation (%s)\n" % - unicode_type(datetime.timedelta(seconds=int(time.time() - opts.start_time)))) + str(datetime.timedelta(seconds=int(time.time() - opts.start_time)))) except (AuthorSortMismatchException, EmptyCatalogException) as e: log.error(" *** Terminated catalog generation: %s ***" % e) except: @@ -500,7 +499,7 @@ def run(self, path_to_output, opts, db, notification=DummyReporter()): if opts.verbose: log.info(" Catalog creation complete (%s)\n" % - unicode_type(datetime.timedelta(seconds=int(time.time() - opts.start_time)))) + str(datetime.timedelta(seconds=int(time.time() - opts.start_time)))) # returns to gui2.actions.catalog:catalog_generated() return catalog.error diff --git a/src/calibre/library/catalogs/epub_mobi_builder.py b/src/calibre/library/catalogs/epub_mobi_builder.py index e83bde404f..388f5b455d 100644 --- a/src/calibre/library/catalogs/epub_mobi_builder.py +++ b/src/calibre/library/catalogs/epub_mobi_builder.py @@ -43,7 +43,7 @@ from calibre.utils.img import scale_image from calibre.utils.localization import get_lang, lang_as_iso639_1 from calibre.utils.zipfile import ZipFile -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems NBSP = '\u00a0' @@ -52,7 +52,7 @@ def makeelement(tag_name, parent, **attrs): ans = parent.makeelement(tag_name) for k, v in attrs.items(): k = k.replace('_', '-').rstrip('-') - ans.set(k, unicode_type(v)) + ans.set(k, str(v)) parent.append(ans) ans.tail = '\n' return ans @@ -252,7 +252,7 @@ def _kf_books_by_author_sorter_author(self, book): index = book['series_index'] integer = int(index) fraction = index - integer - series_index = '%04d%s' % (integer, unicode_type('%0.4f' % fraction).lstrip('0')) + series_index = '%04d%s' % (integer, str('%0.4f' % fraction).lstrip('0')) key = '%s ~%s %s' % (self._kf_author_to_author_sort(book['author']), self.generate_sort_title(book['series']), series_index) @@ -278,7 +278,7 @@ def _kf_books_by_author_sorter_author_sort(self, book, longest_author_sort=60): index = book['series_index'] integer = int(index) fraction = index - integer - series_index = '%04d%s' % (integer, unicode_type('%0.4f' % fraction).lstrip('0')) + series_index = '%04d%s' % (integer, str('%0.4f' % fraction).lstrip('0')) fs = '{:<%d}~{!s}{!s}' % longest_author_sort key = fs.format(capitalize(book['author_sort']), self.generate_sort_title(book['series']), @@ -289,7 +289,7 @@ def _kf_books_by_series_sorter(self, book): index = book['series_index'] integer = int(index) fraction = index - integer - series_index = '%04d%s' % (integer, unicode_type('%0.4f' % fraction).lstrip('0')) + series_index = '%04d%s' % (integer, str('%0.4f' % fraction).lstrip('0')) key = '%s %s' % (self.generate_sort_title(book['series']), series_index) return key @@ -613,7 +613,7 @@ def _log_prefix_rule_match_info(rule, record, matched): for rule in self.prefix_rules: # Literal comparison for Tags field if rule['field'].lower() == 'tags' or rule['field'] == _('Tags'): - if rule['pattern'].lower() in tuple(map(unicode_type.lower, record['tags'])): + if rule['pattern'].lower() in tuple(map(str.lower, record['tags'])): if self.DEBUG and self.opts.verbose: self.opts.log.info(" %s '%s' by %s (%s: Tags includes '%s')" % (rule['prefix'], record['title'], @@ -643,7 +643,7 @@ def _log_prefix_rule_match_info(rule, record, matched): # locale version field_contents = _(repr(field_contents)) try: - if re.search(rule['pattern'], unicode_type(field_contents), + if re.search(rule['pattern'], str(field_contents), re.IGNORECASE) is not None: if self.DEBUG: _log_prefix_rule_match_info(rule, record, field_contents) @@ -715,14 +715,14 @@ def establish_equivalencies(self, item_list, key=None): if icu_upper(c[0]) != last_c: last_c = icu_upper(c[0]) if last_c in exceptions.keys(): - last_c = exceptions[unicode_type(last_c)] + last_c = exceptions[str(last_c)] last_ordnum = ordnum cl_list[idx] = last_c else: if last_ordnum != ordnum: last_c = icu_upper(c[0:ordlen]) if last_c in exceptions.keys(): - last_c = exceptions[unicode_type(last_c)] + last_c = exceptions[str(last_c)] last_ordnum = ordnum else: last_c = cl_list[idx-1] @@ -732,7 +732,7 @@ def establish_equivalencies(self, item_list, key=None): if last_ordnum != ordnum: last_c = icu_upper(c[0:ordlen]) if last_c in exceptions.keys(): - last_c = exceptions[unicode_type(last_c)] + last_c = exceptions[str(last_c)] last_ordnum = ordnum else: last_c = cl_list[idx-1] @@ -1355,7 +1355,7 @@ def format_ncx_text(self, description, dest=None): """ # Kindle TOC descriptions won't render certain characters # Fix up - massaged = xml_replace_entities(unicode_type(description)) + massaged = xml_replace_entities(str(description)) # Replace '&' with '&' # massaged = re.sub("&", "&", massaged) @@ -1422,7 +1422,7 @@ def generate_format_args(self, book): Return: (dict): formatted args for templating """ - series_index = unicode_type(book['series_index']) + series_index = str(book['series_index']) if series_index.endswith('.0'): series_index = series_index[:-2] args = dict( @@ -2701,7 +2701,7 @@ def _generate_html(): series_index = '' if book['series']: series = book['series'] - series_index = unicode_type(book['series_index']) + series_index = str(book['series_index']) if series_index.endswith('.0'): series_index = series_index[:-2] @@ -3078,7 +3078,7 @@ def generate_ncx_descriptions(self, tocTitle): for book in self.books_by_description: sec_id = "book%dID" % int(book['id']) if book['series']: - series_index = unicode_type(book['series_index']) + series_index = str(book['series_index']) if series_index.endswith('.0'): series_index = series_index[:-2] if self.generate_for_kindle_mobi: @@ -4029,7 +4029,7 @@ def generate_unicode_name(self, c): Return: (str): legal XHTML anchor string of unicode character name """ - fullname = ''.join(unicodedata.name(unicode_type(cc)) for cc in c) + fullname = ''.join(unicodedata.name(str(cc)) for cc in c) terms = fullname.split() return "_".join(terms) @@ -4061,7 +4061,7 @@ def get_excluded_tags(self): matched = list(set(record['tags']) & set(excluded_tags)) if matched: for rule in self.opts.exclusion_rules: - if rule[1] == _('Tags') and rule[2] == unicode_type(matched[0]): + if rule[1] == _('Tags') and rule[2] == str(matched[0]): self.opts.log.info(" - '%s' by %s (Exclusion rule '%s')" % (record['title'], record['authors'][0], rule[0])) @@ -4261,7 +4261,7 @@ def process_exclusions(self, data_set): # locale version field_contents = _(repr(field_contents)) - matched = re.search(pat, unicode_type(field_contents), + matched = re.search(pat, str(field_contents), re.IGNORECASE) if matched is not None: if self.opts.verbose: @@ -4350,10 +4350,10 @@ def update_progress_full_step(self, description): if self.opts.cli_environment: log_msg = "%3.0f%% %s" % (self.progress_int * 100, self.progress_string) if self.opts.verbose: - log_msg += " (%s)" % unicode_type(datetime.timedelta(seconds=int(time.time() - self.opts.start_time))) + log_msg += " (%s)" % str(datetime.timedelta(seconds=int(time.time() - self.opts.start_time))) else: log_msg = ("%s (%s)" % (self.progress_string, - unicode_type(datetime.timedelta(seconds=int(time.time() - self.opts.start_time))))) + str(datetime.timedelta(seconds=int(time.time() - self.opts.start_time))))) self.opts.log(log_msg) def update_progress_micro_step(self, description, micro_step_pct): diff --git a/src/calibre/library/comments.py b/src/calibre/library/comments.py index f98008147b..cf934ada8a 100644 --- a/src/calibre/library/comments.py +++ b/src/calibre/library/comments.py @@ -12,7 +12,6 @@ ProcessingInstruction ) from calibre.utils.html2text import html2text -from polyglot.builtins import unicode_type # Hackish - ignoring sentences ending or beginning in numbers to avoid # confusion with decimal points. @@ -49,7 +48,7 @@ def comments_to_html(comments): ''' if not comments: return u'

    ' - if not isinstance(comments, unicode_type): + if not isinstance(comments, str): comments = comments.decode(preferred_encoding, 'replace') if comments.lstrip().startswith('<'): diff --git a/src/calibre/library/custom_columns.py b/src/calibre/library/custom_columns.py index 12882df61c..50bb00bd27 100644 --- a/src/calibre/library/custom_columns.py +++ b/src/calibre/library/custom_columns.py @@ -14,7 +14,7 @@ from calibre.library.field_metadata import FieldMetadata from calibre.utils.date import parse_date from calibre.utils.config import tweaks -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes class CustomColumns: @@ -131,23 +131,23 @@ def adapt_text(x, d): if d['is_multiple']: if x is None: return [] - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): x = x.split(d['multiple_seps']['ui_to_list']) x = [y.strip() for y in x if y.strip()] x = [y.decode(preferred_encoding, 'replace') if not isinstance(y, - unicode_type) else y for y in x] + str) else y for y in x] return [' '.join(y.split()) for y in x] else: - return x if x is None or isinstance(x, unicode_type) else \ + return x if x is None or isinstance(x, str) else \ x.decode(preferred_encoding, 'replace') def adapt_datetime(x, d): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): x = parse_date(x, assume_utc=False, as_utc=False) return x def adapt_bool(x, d): - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = force_unicode(x) x = x.lower() @@ -170,7 +170,7 @@ def adapt_enum(x, d): def adapt_number(x, d): if x is None: return None - if isinstance(x, (unicode_type, bytes)): + if isinstance(x, (str, bytes)): if isinstance(x, bytes): x = force_unicode(x) if x.lower() == 'none': diff --git a/src/calibre/library/database.py b/src/calibre/library/database.py index ebddafcf24..3b405cca0c 100644 --- a/src/calibre/library/database.py +++ b/src/calibre/library/database.py @@ -15,7 +15,6 @@ from calibre.ebooks.metadata import string_to_authors from calibre.utils.serialize import pickle_loads, pickle_dumps from calibre import isbytestring -from polyglot.builtins import unicode_type class Concatenate: @@ -55,7 +54,7 @@ def get(self, *args, **kw): def _connect(path): - if isinstance(path, unicode_type): + if isinstance(path, str): path = path.encode('utf-8') conn = sqlite.connect(path, factory=Connection, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) conn.row_factory = lambda cursor, row : list(row) diff --git a/src/calibre/library/database2.py b/src/calibre/library/database2.py index 61c48218e2..f3a0ec540b 100644 --- a/src/calibre/library/database2.py +++ b/src/calibre/library/database2.py @@ -49,7 +49,7 @@ from calibre.db.categories import Tag, CATEGORY_SORTS from calibre.utils.localization import (canonicalize_lang, calibre_langcode_to_name) -from polyglot.builtins import iteritems, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, string_or_bytes copyfile = os.link if hasattr(os, 'link') else shutil.copyfile SPOOL_SIZE = 30*1024*1024 @@ -93,7 +93,7 @@ def library_id(self): if self._library_id_ is None: ans = self.conn.get('SELECT uuid FROM library_id', all=False) if ans is None: - ans = unicode_type(uuid.uuid4()) + ans = str(uuid.uuid4()) self.library_id = ans else: self._library_id_ = ans @@ -101,7 +101,7 @@ def library_id(self): @library_id.setter def library_id(self, val): - self._library_id_ = unicode_type(val) + self._library_id_ = str(val) self.conn.executescript(''' DELETE FROM library_id; INSERT INTO library_id (uuid) VALUES ("%s"); @@ -258,11 +258,11 @@ def initialize_dynamic(self): from calibre.library.coloring import migrate_old_rule old_rules = [] for i in range(1, 6): - col = self.prefs.get('column_color_name_'+unicode_type(i), None) - templ = self.prefs.get('column_color_template_'+unicode_type(i), None) + col = self.prefs.get('column_color_name_'+str(i), None) + templ = self.prefs.get('column_color_template_'+str(i), None) if col and templ: try: - del self.prefs['column_color_name_'+unicode_type(i)] + del self.prefs['column_color_name_'+str(i)] rules = migrate_old_rule(self.field_metadata, templ) for templ in rules: old_rules.append((col, templ)) @@ -328,10 +328,10 @@ def migrate_preference(key, default): prints('found user category case overlap', catmap[uc]) cat = catmap[uc][0] suffix = 1 - while icu_lower((cat + unicode_type(suffix))) in catmap: + while icu_lower((cat + str(suffix))) in catmap: suffix += 1 - prints('Renaming user category %s to %s'%(cat, cat+unicode_type(suffix))) - user_cats[cat + unicode_type(suffix)] = user_cats[cat] + prints('Renaming user category %s to %s'%(cat, cat+str(suffix))) + user_cats[cat + str(suffix)] = user_cats[cat] del user_cats[cat] cats_changed = True if cats_changed: @@ -452,7 +452,7 @@ def migrate_preference(key, default): # account for the series index column. Field_metadata knows that # the series index is one larger than the series. If you change # it here, be sure to change it there as well. - self.FIELD_MAP[unicode_type(col)+'_index'] = base = base+1 + self.FIELD_MAP[str(col)+'_index'] = base = base+1 self.field_metadata.set_field_record_index( self.custom_column_num_map[col]['label']+'_index', base, @@ -1086,7 +1086,7 @@ def get_metadata(self, idx, index_is_id=False, get_cover=False, def has_book(self, mi): title = mi.title if title: - if not isinstance(title, unicode_type): + if not isinstance(title, str): title = title.decode(preferred_encoding, 'replace') return bool(self.conn.get('SELECT id FROM books where title=?', (title,), all=False)) return False @@ -1762,8 +1762,8 @@ def clean_user_categories(self): if len(comps) == 0: i = 1 while True: - if unicode_type(i) not in user_cats: - new_cats[unicode_type(i)] = user_cats[k] + if str(i) not in user_cats: + new_cats[str(i)] = user_cats[k] break i += 1 else: @@ -1989,7 +1989,7 @@ def get_categories(self, sort='name', ids=None): formatter = calibre_langcode_to_name items = [v for v in tcategories[category].values() if v.c > 0] else: - formatter = (lambda x:unicode_type(x)) + formatter = (lambda x:str(x)) items = [v for v in tcategories[category].values() if v.c > 0] # sort the list @@ -2460,7 +2460,7 @@ def _set_authors(self, id, authors, allow_case_change=False): if not a: continue a = a.strip().replace(',', '|') - if not isinstance(a, unicode_type): + if not isinstance(a, str): a = a.decode(preferred_encoding, 'replace') aus = self.conn.get('SELECT id, name, sort FROM authors WHERE name=?', (a,)) if aus: @@ -2619,7 +2619,7 @@ def set_languages(self, book_id, languages, notify=True, commit=True): def set_timestamp(self, id, dt, notify=True, commit=True): if dt: - if isinstance(dt, (unicode_type, bytes)): + if isinstance(dt, (str, bytes)): dt = parse_date(dt, as_utc=True, assume_utc=False) self.conn.execute('UPDATE books SET timestamp=? WHERE id=?', (dt, id)) self.data.set(id, self.FIELD_MAP['timestamp'], dt, row_is_id=True) @@ -2648,7 +2648,7 @@ def set_publisher(self, id, publisher, notify=True, commit=True, books_to_refresh = {id} if publisher: case_change = False - if not isinstance(publisher, unicode_type): + if not isinstance(publisher, str): publisher = publisher.decode(preferred_encoding, 'replace') pubx = self.conn.get('''SELECT id,name from publishers WHERE name=?''', (publisher,)) @@ -3093,7 +3093,7 @@ def set_tags(self, id, tags, append=False, notify=True, commit=True, tag = tag.strip() if not tag: continue - if not isinstance(tag, unicode_type): + if not isinstance(tag, str): tag = tag.decode(preferred_encoding, 'replace') existing_tags = self.all_tags() lt = [t.lower() for t in existing_tags] @@ -3174,7 +3174,7 @@ def set_series(self, id, series, notify=True, commit=True, allow_case_change=Tru books_to_refresh = {id} if series: case_change = False - if not isinstance(series, unicode_type): + if not isinstance(series, str): series = series.decode(preferred_encoding, 'replace') series = series.strip() series = ' '.join(series.split()) @@ -3545,7 +3545,7 @@ def import_book(self, mi, formats, notify=True, import_hooks=True, aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors) if isinstance(aus, bytes): aus = aus.decode(preferred_encoding, 'replace') - title = mi.title if isinstance(mi.title, unicode_type) else \ + title = mi.title if isinstance(mi.title, str) else \ mi.title.decode(preferred_encoding, 'replace') obj = self.conn.execute('INSERT INTO books(title, series_index, author_sort) VALUES (?, ?, ?)', (title, series_index, aus)) @@ -3615,7 +3615,7 @@ def move_library_to(self, newloc, progress=None): os.remove(dest) shutil.copyfile(src, dest) x = path_map[x] - if not isinstance(x, unicode_type): + if not isinstance(x, str): x = x.decode(filesystem_encoding, 'replace') progress(x) diff --git a/src/calibre/library/prefs.py b/src/calibre/library/prefs.py index 9e1556eb98..4ef2cc8795 100644 --- a/src/calibre/library/prefs.py +++ b/src/calibre/library/prefs.py @@ -11,7 +11,7 @@ from calibre.constants import preferred_encoding from calibre.utils.config import to_json, from_json from calibre import prints -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class DBPrefs(dict): @@ -30,7 +30,7 @@ def __init__(self, db): dict.__setitem__(self, key, val) def raw_to_object(self, raw): - if not isinstance(raw, unicode_type): + if not isinstance(raw, str): raw = raw.decode(preferred_encoding) return json.loads(raw, object_hook=from_json) diff --git a/src/calibre/library/save_to_disk.py b/src/calibre/library/save_to_disk.py index 6872a3672f..cc8cd9c0c9 100644 --- a/src/calibre/library/save_to_disk.py +++ b/src/calibre/library/save_to_disk.py @@ -19,7 +19,6 @@ from calibre.utils.date import as_local_time from calibre import strftime, prints, sanitize_file_name from calibre.db.lazy import FormatsList -from polyglot.builtins import unicode_type plugboard_any_device_value = 'any device' plugboard_any_format_value = 'any format' @@ -132,7 +131,7 @@ def preprocess_template(template): template = template.replace('//', '/') template = template.replace('{author}', '{authors}') template = template.replace('{tag}', '{tags}') - if not isinstance(template, unicode_type): + if not isinstance(template, str): template = template.decode(preferred_encoding, 'replace') return template @@ -215,7 +214,7 @@ def get_components(template, mi, id, timefmt='%b %Y', length=250, if hasattr(mi, 'last_modified') and hasattr(mi.last_modified, 'timetuple'): format_args['last_modified'] = strftime(timefmt, mi.last_modified.timetuple()) - format_args['id'] = unicode_type(id) + format_args['id'] = str(id) # Now format the custom fields custom_metadata = mi.get_all_user_metadata(make_copy=False) for key in custom_metadata: @@ -234,7 +233,7 @@ def get_components(template, mi, id, timefmt='%b %Y', length=250, divide_by=2.0) elif cm['datatype'] in ['int', 'float']: if format_args[key] != 0: - format_args[key] = unicode_type(format_args[key]) + format_args[key] = str(format_args[key]) else: format_args[key] = '' if safe_format: @@ -245,7 +244,7 @@ def get_components(template, mi, id, timefmt='%b %Y', length=250, components = [x.strip() for x in components.split('/')] components = [sanitize_func(x) for x in components if x] if not components: - components = [unicode_type(id)] + components = [str(id)] if to_lowercase: components = [x.lower() for x in components] if replace_whitespace: @@ -358,7 +357,7 @@ def do_save_book_to_disk(db, book_id, mi, plugboards, return not formats_written, book_id, mi.title for fmt in formats: - fmt_path = base_path+'.'+unicode_type(fmt) + fmt_path = base_path+'.'+str(fmt) try: db.copy_format_to(book_id, fmt, fmt_path) formats_written = True diff --git a/src/calibre/library/schema_upgrades.py b/src/calibre/library/schema_upgrades.py index b11d9dc161..d71c90fd5c 100644 --- a/src/calibre/library/schema_upgrades.py +++ b/src/calibre/library/schema_upgrades.py @@ -9,7 +9,7 @@ import os from calibre.utils.date import isoformat, DEFAULT_DATE -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues class SchemaUpgrade: @@ -593,10 +593,10 @@ def upgrade_version_19(self): existing = frozenset(map(int, custom_recipes)) if id_ in existing: id_ = max(existing) + 1000 - id_ = unicode_type(id_) + id_ = str(id_) fname = custom_recipe_filename(id_, title) custom_recipes[id_] = (title, fname) - if isinstance(script, unicode_type): + if isinstance(script, str): script = script.encode('utf-8') with open(os.path.join(bdir, fname), 'wb') as f: f.write(script) diff --git a/src/calibre/library/sqlite.py b/src/calibre/library/sqlite.py index c2a901d7ad..b634de5c24 100644 --- a/src/calibre/library/sqlite.py +++ b/src/calibre/library/sqlite.py @@ -23,7 +23,7 @@ from calibre.utils.icu import sort_key from calibre_extensions import speedup as _c_speedup from calibre import prints -from polyglot.builtins import cmp, native_string_type, unicode_type +from polyglot.builtins import cmp, native_string_type from polyglot import reprlib from polyglot.queue import Queue @@ -268,7 +268,7 @@ def do_connect(path, row_factory=None): conn.create_function('title_sort', 1, title_sort) conn.create_function('author_to_author_sort', 1, _author_to_author_sort) - conn.create_function('uuid4', 0, lambda : unicode_type(uuid.uuid4())) + conn.create_function('uuid4', 0, lambda : str(uuid.uuid4())) # Dummy functions for dynamically created filters conn.create_function('books_list_filter', 1, lambda x: 1) conn.create_collation(native_string_type('icucollate'), icu_collator) @@ -321,7 +321,7 @@ def run(self): break except OperationalError as err: # Retry if unable to open db file - e = unicode_type(err) + e = str(err) if 'unable to open' not in e or i == 2: if 'unable to open' in e: prints('Unable to open database for func', @@ -341,7 +341,7 @@ class DatabaseException(Exception): def __init__(self, err, tb): tb = '\n\t'.join(('\tRemote'+tb).splitlines()) try: - msg = unicode_type(err) +'\n' + tb + msg = str(err) +'\n' + tb except: msg = repr(err) + '\n' + tb Exception.__init__(self, msg) @@ -362,7 +362,7 @@ def run(self, *args, **kwargs): ok, res = self.proxy.results.get() if not ok: if isinstance(res[0], IntegrityError): - raise IntegrityError(unicode_type(res[0])) + raise IntegrityError(str(res[0])) raise DatabaseException(*res) return res return run diff --git a/src/calibre/linux.py b/src/calibre/linux.py index 1037c3dd0a..e78ed1c00c 100644 --- a/src/calibre/linux.py +++ b/src/calibre/linux.py @@ -13,7 +13,7 @@ from calibre.customize.ui import all_input_formats from calibre.ptempfile import TemporaryDirectory from calibre import CurrentDir -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems entry_points = { @@ -276,7 +276,7 @@ def get_options(self, parser, cover_opts=('--cover',), opf_opts=('--opf',), h = opt.help or '' h = h.replace('"', "'").replace('[', '(').replace( ']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'") - h = h.replace('%default', unicode_type(opt.default)) + h = h.replace('%default', str(opt.default)) arg = '' if opt.takes_value(): arg = ':"%s":'%h @@ -434,7 +434,7 @@ def do_ebook_edit(self, f): h = opt.help or '' h = h.replace('"', "'").replace('[', '(').replace( ']', ')').replace('\n', ' ').replace(':', '\\:').replace('`', "'") - h = h.replace('%default', unicode_type(opt.default)) + h = h.replace('%default', str(opt.default)) help_txt = '"[%s]"'%h opt_lines.append(ostrings + help_txt + ' \\') opt_lines = ('\n' + (' ' * 8)).join(opt_lines) @@ -831,7 +831,7 @@ def setup_completion(self): # {{{ self.info('Installing bash completion to:', bash_comp_dest+os.sep) write_completion(self, bash_comp_dest, zsh) except TypeError as err: - if 'resolve_entities' in unicode_type(err): + if 'resolve_entities' in str(err): print('You need python-lxml >= 2.0.5 for calibre') sys.exit(1) raise @@ -879,11 +879,11 @@ def install_xdg_junk(self, cc, env): def install_single_icon(iconsrc, basename, size, context, is_last_icon=False): filename = '%s-%s.png' % (basename, size) render_img(iconsrc, filename, width=int(size), height=int(size)) - cmd = ['xdg-icon-resource', 'install', '--noupdate', '--context', context, '--size', unicode_type(size), filename, basename] + cmd = ['xdg-icon-resource', 'install', '--noupdate', '--context', context, '--size', str(size), filename, basename] if is_last_icon: del cmd[2] cc(cmd) - self.icon_resources.append((context, basename, unicode_type(size))) + self.icon_resources.append((context, basename, str(size))) def install_icons(iconsrc, basename, context, is_last_icon=False): sizes = (16, 32, 48, 64, 128, 256) @@ -1252,7 +1252,7 @@ def write_appdata(key, entry, base, translators): fpath = os.path.join(base, '%s.metainfo.xml' % key) screenshots = E.screenshots() for w, h, url in entry['screenshots']: - s = E.screenshot(E.image(url, width=unicode_type(w), height=unicode_type(h))) + s = E.screenshot(E.image(url, width=str(w), height=str(h))) screenshots.append(s) screenshots[0].set('type', 'default') description = E.description() diff --git a/src/calibre/spell/dictionary.py b/src/calibre/spell/dictionary.py index bff129ae22..b1b7f73d04 100644 --- a/src/calibre/spell/dictionary.py +++ b/src/calibre/spell/dictionary.py @@ -19,7 +19,7 @@ from calibre.utils.config import JSONConfig from calibre.utils.icu import capitalize from calibre.utils.localization import get_lang, get_system_locale -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues Dictionary = namedtuple('Dictionary', 'primary_locale locales dicpath affpath builtin name id') LoadedDictionary = namedtuple('Dictionary', 'primary_locale locales obj builtin name id') @@ -397,7 +397,7 @@ def add_suggestion(w, ans): if d is not None: try: - ans = d.obj.suggest(unicode_type(word).replace('\u2010', '-')) + ans = d.obj.suggest(str(word).replace('\u2010', '-')) except ValueError: pass else: diff --git a/src/calibre/srv/ajax.py b/src/calibre/srv/ajax.py index 2ea45c4642..661283c3a5 100644 --- a/src/calibre/srv/ajax.py +++ b/src/calibre/srv/ajax.py @@ -6,7 +6,7 @@ __copyright__ = '2015, Kovid Goyal ' from functools import partial -from polyglot.builtins import iteritems, itervalues, unicode_type, string_or_bytes +from polyglot.builtins import iteritems, itervalues, string_or_bytes from itertools import cycle from calibre import force_unicode @@ -115,7 +115,7 @@ def book_to_json(ctx, rd, db, book_id, dbtags[category] = ctx.url_for( books_in, encoded_category=encode_name(tag.category if tag.category else key), - encoded_item=encode_name(tag.original_name if tag.id is None else unicode_type(tag.id)), + encoded_item=encode_name(tag.original_name if tag.id is None else str(tag.id)), library_id=db.server_library_id ) break @@ -134,7 +134,7 @@ def book_to_json(ctx, rd, db, book_id, for device_class in device_plugins(): if device_class.__class__.__name__ == device_for_template: template = device_class.save_template() - data['_filename_'] = create_upload_path(mi, unicode_type(book_id), + data['_filename_'] = create_upload_path(mi, str(book_id), template, sanitize, path_type=posixpath) break @@ -445,7 +445,7 @@ def category(ctx, rd, encoded_name, library_id): 'average_rating': x.avg_rating, 'count': x.count, 'url': ctx.url_for(books_in, encoded_category=encode_name(x.category if x.category else toplevel), - encoded_item=encode_name(x.original_name if x.id is None else unicode_type(x.id)), + encoded_item=encode_name(x.original_name if x.id is None else str(x.id)), library_id=db.server_library_id ), 'has_children': x.original_name in children, @@ -551,7 +551,7 @@ def search_result(ctx, rd, db, query, num, offset, sort, sort_order, vl=''): 'vl': vl, } if parse_error is not None: - ans['bad_restriction'] = unicode_type(parse_error) + ans['bad_restriction'] = str(parse_error) return ans diff --git a/src/calibre/srv/content.py b/src/calibre/srv/content.py index 9d2c614f68..daab3cc34e 100644 --- a/src/calibre/srv/content.py +++ b/src/calibre/srv/content.py @@ -9,7 +9,6 @@ from io import BytesIO from threading import Lock from contextlib import suppress -from polyglot.builtins import unicode_type from functools import partial from calibre import fit_image, sanitize_file_name @@ -165,7 +164,7 @@ def book_filename(rd, book_id, mi, fmt, as_encoded_unicode=False): if as_encoded_unicode: # See https://tools.ietf.org/html/rfc6266 fname = sanitize_file_name(fname).encode('utf-8') - fname = unicode_type(quote(fname)) + fname = str(quote(fname)) else: fname = ascii_filename(fname).replace('"', '_') if ext == 'kepub' and 'Kobo Touch' in rd.inheaders.get('User-Agent', ''): diff --git a/src/calibre/srv/handler.py b/src/calibre/srv/handler.py index d2451cc556..c2ce1fdcdd 100644 --- a/src/calibre/srv/handler.py +++ b/src/calibre/srv/handler.py @@ -15,7 +15,7 @@ from calibre.srv.users import UserManager from calibre.utils.date import utcnow from calibre.utils.search_query_parser import ParseException -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues class Context: @@ -148,7 +148,7 @@ def get_tag_browser(self, request_data, db, opts, render, vl=''): if old is None or old[0] <= db.last_modified(): categories = db.get_categories(book_ids=restrict_to_ids, sort=opts.sort_by, first_letter_sort=opts.collapse_model == 'first letter') data = json.dumps(render(db, categories), ensure_ascii=False) - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') cache[key] = old = (utcnow(), data) if len(cache) > self.CATEGORY_CACHE_SIZE: diff --git a/src/calibre/srv/http_response.py b/src/calibre/srv/http_response.py index 274a0b0105..40cd17cc73 100644 --- a/src/calibre/srv/http_response.py +++ b/src/calibre/srv/http_response.py @@ -29,8 +29,7 @@ from calibre.utils.speedups import ReadOnlyFileBuffer from polyglot import http_client, reprlib from polyglot.builtins import ( - error_message, iteritems, itervalues, reraise, string_or_bytes, - unicode_type + error_message, iteritems, itervalues, reraise, string_or_bytes ) Range = namedtuple('Range', 'start stop size') @@ -255,7 +254,7 @@ def generate_static_output(self, name, generator, content_type='text/html; chars def filesystem_file_with_custom_etag(self, output, *etag_parts): etag = hashlib.sha1() - tuple(map(lambda x:etag.update(unicode_type(x).encode('utf-8')), etag_parts)) + tuple(map(lambda x:etag.update(str(x).encode('utf-8')), etag_parts)) return ETaggedFile(output, etag.hexdigest()) def filesystem_file_with_constant_etag(self, output, etag_as_hexencoded_string): @@ -321,8 +320,8 @@ def filesystem_file_output(output, outheaders, stat_result): if etag is None: oname = output.name or '' if not isinstance(oname, string_or_bytes): - oname = unicode_type(oname) - etag = hashlib.sha1((unicode_type(stat_result.st_mtime) + force_unicode(oname)).encode('utf-8')).hexdigest() + oname = str(oname) + etag = hashlib.sha1((str(stat_result.st_mtime) + force_unicode(oname)).encode('utf-8')).hexdigest() else: output = output.output etag = '"%s"' % etag @@ -366,7 +365,7 @@ def __init__(self, output, etag=None): class StaticOutput: def __init__(self, data): - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') self.data = data self.etag = '"%s"' % hashlib.sha1(data).hexdigest() @@ -659,7 +658,7 @@ def finalize_output(self, output, request, is_http1): if 'Content-Type' not in outheaders: output_name = output.name if not isinstance(output_name, string_or_bytes): - output_name = unicode_type(output_name) + output_name = str(output_name) mt = guess_type(output_name)[0] if mt: if mt in {'text/plain', 'text/html', 'application/javascript', 'text/css'}: diff --git a/src/calibre/srv/legacy.py b/src/calibre/srv/legacy.py index 16a8f14703..0cabae678d 100644 --- a/src/calibre/srv/legacy.py +++ b/src/calibre/srv/legacy.py @@ -18,7 +18,7 @@ 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 polyglot.builtins import iteritems, string_or_bytes, as_bytes, unicode_type +from polyglot.builtins import iteritems, string_or_bytes, as_bytes from polyglot.urllib import urlencode # /mobile {{{ @@ -62,10 +62,10 @@ def build_search_box(num, search, sort, order, ctx, field_metadata, library_id): num_select = E.select(name='num') for option in (5, 10, 25, 100): - kwargs = {'value':unicode_type(option)} + kwargs = {'value':str(option)} if option == num: kwargs['SELECTED'] = 'SELECTED' - num_select.append(E.option(unicode_type(option), **kwargs)) + num_select.append(E.option(str(option), **kwargs)) num_select.tail = ' books matching ' form.append(num_select) diff --git a/src/calibre/srv/loop.py b/src/calibre/srv/loop.py index 70c18092dc..e0f2c89e34 100644 --- a/src/calibre/srv/loop.py +++ b/src/calibre/srv/loop.py @@ -30,7 +30,7 @@ from calibre.utils.mdns import get_external_ip from calibre.utils.monotonic import monotonic from calibre.utils.socket_inheritance import set_socket_inherit -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot.queue import Empty, Full READ, WRITE, RDWR, WAIT = 'READ', 'WRITE', 'RDWR', 'WAIT' @@ -503,7 +503,7 @@ def serve(self): self.socket.listen(min(socket.SOMAXCONN, 128)) self.bound_address = ba = self.socket.getsockname() if isinstance(ba, tuple): - ba = ':'.join(map(unicode_type, ba)) + ba = ':'.join(map(str, ba)) self.pool.start() with TemporaryDirectory(prefix='srv-') as tdir: self.tdir = tdir diff --git a/src/calibre/srv/manage_users_cli.py b/src/calibre/srv/manage_users_cli.py index 1c841a38a6..16fce3d214 100644 --- a/src/calibre/srv/manage_users_cli.py +++ b/src/calibre/srv/manage_users_cli.py @@ -8,7 +8,7 @@ from calibre import prints from calibre.constants import preferred_encoding, iswindows from calibre.utils.config import OptionParser -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems def create_subcommand_parser(name, usage): @@ -123,7 +123,7 @@ def choice( len(choices), _('default'), default + 1) reply = get_input(prompt) if not reply and default is not None: - reply = unicode_type(default + 1) + reply = str(default + 1) if not reply: prints(_('No choice selected, exiting...')) raise SystemExit(0) diff --git a/src/calibre/srv/metadata.py b/src/calibre/srv/metadata.py index e2feb62506..dc08e6d9f7 100644 --- a/src/calibre/srv/metadata.py +++ b/src/calibre/srv/metadata.py @@ -21,7 +21,7 @@ from calibre.utils.localization import calibre_langcode_to_name from calibre.library.comments import comments_to_html, markdown from calibre.library.field_metadata import category_icon_map -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot.urllib import quote IGNORED_FIELDS = frozenset('cover ondevice path marked au_map'.split()) @@ -116,7 +116,7 @@ def category_as_json(items, category, display_name, count, tooltip=None, parent= ans['is_user_category'] = True if is_first_letter: ans['is_first_letter'] = True - item_id = 'c' + unicode_type(len(items)) + item_id = 'c' + str(len(items)) items[item_id] = ans return item_id diff --git a/src/calibre/srv/opds.py b/src/calibre/srv/opds.py index 30aca1aa01..f19dd164cf 100644 --- a/src/calibre/srv/opds.py +++ b/src/calibre/srv/opds.py @@ -28,7 +28,7 @@ from calibre.utils.search_query_parser import ParseException from calibre.utils.xml_parse import safe_xml_fromstring from polyglot.binary import as_hex_unicode, from_hex_unicode -from polyglot.builtins import as_bytes, iteritems, unicode_type +from polyglot.builtins import as_bytes, iteritems from polyglot.urllib import unquote_plus, urlencode @@ -37,7 +37,7 @@ def atom(ctx, rd, endpoint, output): rd.outheaders.set('Calibre-Instance-Id', force_unicode(prefs['installation_uuid'], 'utf-8'), replace_all=True) if isinstance(output, bytes): ans = output # Assume output is already UTF-8 XML - elif isinstance(output, unicode_type): + elif isinstance(output, str): ans = output.encode('utf-8') else: ans = etree.tostring(output, encoding='utf-8', xml_declaration=True, pretty_print=True) @@ -144,7 +144,7 @@ def CATALOG_ENTRY(item, item_kind, request_context, updated, catalog_name, id_ = 'calibre:category:'+item.name iid = 'N' + item.name if item.id is not None: - iid = 'I' + unicode_type(item.id) + iid = 'I' + str(item.id) iid += ':'+item_kind href = request_context.url_for('/opds/category', category=as_hex_unicode(catalog_name), which=as_hex_unicode(iid)) link = NAVLINK(href=href) @@ -203,9 +203,9 @@ def ACQUISITION_ENTRY(book_id, updated, request_context): fm['is_multiple']['ui_to_list'], joinval=fm['is_multiple']['list_to_ui'])))) elif datatype == 'comments' or (fm['datatype'] == 'composite' and fm['display'].get('contains_html', False)): - extra.append('%s: %s
    '%(xml(name), comments_to_html(unicode_type(val)))) + extra.append('%s: %s
    '%(xml(name), comments_to_html(str(val)))) else: - extra.append('%s: %s
    '%(xml(name), xml(unicode_type(val)))) + extra.append('%s: %s
    '%(xml(name), xml(str(val)))) if mi.comments: comments = comments_to_html(mi.comments) extra.append(comments) @@ -228,7 +228,7 @@ def ACQUISITION_ENTRY(book_id, updated, request_context): link = E.link(type=mt, href=get(what=fmt), rel="http://opds-spec.org/acquisition") ffm = fm.get(fmt.upper()) if ffm: - link.set('length', unicode_type(ffm['size'])) + link.set('length', str(ffm['size'])) link.set('mtime', ffm['mtime'].isoformat()) ans.append(link) ans.append(E.link(type='image/jpeg', href=get(what='cover'), rel="http://opds-spec.org/cover")) @@ -571,7 +571,7 @@ def opds_category(ctx, rd, category, which): ids = rc.db.get_books_for_category(q, which) & rc.allowed_book_ids() sort_by = 'series' if category == 'series' else 'title' - return get_acquisition_feed(rc, ids, offset, page_url, up_url, 'calibre-category:'+category+':'+unicode_type(which), sort_by=sort_by) + return get_acquisition_feed(rc, ids, offset, page_url, up_url, 'calibre-category:'+category+':'+str(which), sort_by=sort_by) @endpoint('/opds/categorygroup/{category}/{which}', postprocess=atom) diff --git a/src/calibre/srv/render_book.py b/src/calibre/srv/render_book.py index 72e760bd49..aab2996f2a 100644 --- a/src/calibre/srv/render_book.py +++ b/src/calibre/srv/render_book.py @@ -47,7 +47,7 @@ as_base64_unicode as encode_component, from_base64_bytes, from_base64_unicode as decode_component ) -from polyglot.builtins import as_bytes, iteritems, unicode_type +from polyglot.builtins import as_bytes, iteritems from polyglot.urllib import quote, urlparse RENDER_VERSION = 1 @@ -108,7 +108,7 @@ def link_replacer(base, url): frag = urlunquote(frag) url = resource_template.format(encode_url(name, frag)) else: - if isinstance(name, unicode_type): + if isinstance(name, str): name = name.encode('utf-8') url = 'missing:' + force_unicode(quote(name), 'utf-8') changed.add(base) @@ -770,7 +770,7 @@ def get_stored_annotations(container, bookmark_data): from calibre.ebooks.oeb.iterator.bookmarks import parse_bookmarks for bm in parse_bookmarks(raw): - if bm['type'] == 'cfi' and isinstance(bm['pos'], unicode_type): + if bm['type'] == 'cfi' and isinstance(bm['pos'], str): spine_index = (1 + bm['spine']) * 2 epubcfi = 'epubcfi(/{}/{})'.format(spine_index, bm['pos'].lstrip('/')) title = bm.get('title') diff --git a/src/calibre/srv/routes.py b/src/calibre/srv/routes.py index e7713700f9..6feb8c1d73 100644 --- a/src/calibre/srv/routes.py +++ b/src/calibre/srv/routes.py @@ -11,7 +11,7 @@ from calibre.srv.errors import HTTPSimpleResponse, HTTPNotFound, RouteError from calibre.srv.utils import http_date from calibre.utils.serialize import msgpack_dumps, json_dumps, MSGPACK_MIME -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot import http_client from polyglot.urllib import quote as urlquote @@ -142,7 +142,7 @@ def route_error(msg): default = self.defaults[name] = eval(default) if isinstance(default, numbers.Number): self.type_checkers[name] = type(default) - if is_sponge and not isinstance(default, unicode_type): + if is_sponge and not isinstance(default, str): raise route_error('Soak up path component must have a default value of string type') else: if found_optional_part is not False: @@ -201,9 +201,9 @@ def url_for(self, **kwargs): raise RouteError('The variable(s) %s are not part of the route: %s' % (','.join(unknown), self.endpoint.route)) def quoted(x): - if not isinstance(x, (unicode_type, bytes)): - x = unicode_type(x) - if isinstance(x, unicode_type): + if not isinstance(x, (str, bytes)): + x = str(x) + if isinstance(x, str): x = x.encode('utf-8') return urlquote(x, '') args = {k:'' for k in self.defaults} diff --git a/src/calibre/srv/standalone.py b/src/calibre/srv/standalone.py index ef4e2063d6..695f064996 100644 --- a/src/calibre/srv/standalone.py +++ b/src/calibre/srv/standalone.py @@ -24,7 +24,7 @@ from calibre.utils.config import prefs from calibre.utils.localization import localize_user_manual_link from calibre.utils.lock import singleinstance -from polyglot.builtins import error_message, unicode_type +from polyglot.builtins import error_message from calibre_extensions import speedup @@ -236,7 +236,7 @@ def main(args=sys.argv): daemonize() if opts.pidfile: with lopen(opts.pidfile, 'wb') as f: - f.write(unicode_type(os.getpid()).encode('ascii')) + f.write(str(os.getpid()).encode('ascii')) signal.signal(signal.SIGTERM, lambda s, f: server.stop()) if not getattr(opts, 'daemonize', False) and not iswindows: signal.signal(signal.SIGHUP, lambda s, f: server.stop()) diff --git a/src/calibre/srv/tests/http.py b/src/calibre/srv/tests/http.py index 3c03e09dbe..e3464218e9 100644 --- a/src/calibre/srv/tests/http.py +++ b/src/calibre/srv/tests/http.py @@ -13,7 +13,7 @@ from calibre.srv.tests.base import BaseTest, TestServer from calibre.srv.utils import eintr_retry_call from calibre.utils.monotonic import monotonic -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems from polyglot import http_client is_ci = os.environ.get('CI', '').lower() == 'true' @@ -186,7 +186,7 @@ def raw_send(conn, raw): r = conn.getresponse() self.ae(r.status, http_client.NOT_FOUND) self.assertIsNotNone(r.getheader('Date', None)) - self.ae(r.getheader('Content-Length'), unicode_type(len(body))) + self.ae(r.getheader('Content-Length'), str(len(body))) self.ae(r.getheader('Content-Type'), 'text/plain; charset=UTF-8') self.ae(len(r.getheaders()), 3) self.ae(r.read(), b'') @@ -331,7 +331,7 @@ def handler(conn): conn = server.connect() conn.request('GET', '/an_etagged_path', headers={'Accept-Encoding':'gzip'}) r = conn.getresponse() - self.ae(unicode_type(len(raw)), r.getheader('Calibre-Uncompressed-Length')) + self.ae(str(len(raw)), r.getheader('Calibre-Uncompressed-Length')) self.ae(r.status, http_client.OK), self.ae(zlib.decompress(r.read(), 16+zlib.MAX_WBITS), raw) # Test dynamic etagged content @@ -361,25 +361,25 @@ def edfunc(): conn = server.connect() conn.request('GET', '/test') r = conn.getresponse() - etag = unicode_type(r.getheader('ETag')) + etag = str(r.getheader('ETag')) self.assertTrue(etag) self.ae(r.getheader('Content-Type'), guess_type(f.name)[0]) - self.ae(unicode_type(r.getheader('Accept-Ranges')), 'bytes') + self.ae(str(r.getheader('Accept-Ranges')), 'bytes') self.ae(int(r.getheader('Content-Length')), len(fdata)) self.ae(r.status, http_client.OK), self.ae(r.read(), fdata) conn.request('GET', '/test', headers={'Range':'bytes=2-25'}) r = conn.getresponse() self.ae(r.status, http_client.PARTIAL_CONTENT) - self.ae(unicode_type(r.getheader('Accept-Ranges')), 'bytes') - self.ae(unicode_type(r.getheader('Content-Range')), 'bytes 2-25/%d' % len(fdata)) + self.ae(str(r.getheader('Accept-Ranges')), 'bytes') + self.ae(str(r.getheader('Content-Range')), 'bytes 2-25/%d' % len(fdata)) self.ae(int(r.getheader('Content-Length')), 24) self.ae(r.read(), fdata[2:26]) conn.request('GET', '/test', headers={'Range':'bytes=100000-'}) r = conn.getresponse() self.ae(r.status, http_client.REQUESTED_RANGE_NOT_SATISFIABLE) - self.ae(unicode_type(r.getheader('Content-Range')), 'bytes */%d' % len(fdata)) + self.ae(str(r.getheader('Content-Range')), 'bytes */%d' % len(fdata)) conn.request('GET', '/test', headers={'Range':'bytes=25-50', 'If-Range':etag}) r = conn.getresponse() diff --git a/src/calibre/srv/tests/loop.py b/src/calibre/srv/tests/loop.py index 17e7fd56b4..109af82981 100644 --- a/src/calibre/srv/tests/loop.py +++ b/src/calibre/srv/tests/loop.py @@ -16,7 +16,6 @@ from calibre.ptempfile import TemporaryDirectory from calibre.utils.certgen import create_server_cert from calibre.utils.monotonic import monotonic -from polyglot.builtins import unicode_type from polyglot import http_client is_ci = os.environ.get('CI', '').lower() == 'true' @@ -218,7 +217,7 @@ def test_socket_activation(self): s.bind(('localhost', 0)) port = s.getsockname()[1] self.ae(s.fileno(), 3) - os.environ['LISTEN_PID'] = unicode_type(os.getpid()) + os.environ['LISTEN_PID'] = str(os.getpid()) os.environ['LISTEN_FDS'] = '1' with TestServer(lambda data:(data.path[0].encode('utf-8') + data.read()), allow_socket_preallocation=True) as server: conn = server.connect() diff --git a/src/calibre/srv/tests/web_sockets.py b/src/calibre/srv/tests/web_sockets.py index 6b3159e4d5..0803697a9e 100644 --- a/src/calibre/srv/tests/web_sockets.py +++ b/src/calibre/srv/tests/web_sockets.py @@ -14,7 +14,6 @@ PING, PONG, PROTOCOL_ERROR, CONTINUATION, INCONSISTENT_DATA, CONTROL_CODES) from calibre.utils.monotonic import monotonic from calibre.utils.socket_inheritance import set_socket_inherit -from polyglot.builtins import unicode_type from polyglot.binary import as_base64_unicode HANDSHAKE_STR = '''\ @@ -132,7 +131,7 @@ def read_messages(self): def write_message(self, msg, chunk_size=None): if isinstance(msg, tuple): opcode, msg = msg - if isinstance(msg, unicode_type): + if isinstance(msg, str): msg = msg.encode('utf-8') return self.write_frame(1, opcode, msg) w = MessageWriter(msg, self.mask, chunk_size) @@ -147,7 +146,7 @@ def write_frame(self, fin=1, opcode=CLOSE, payload=b'', rsv=0, mask=True): self.socket.sendall(frame) def write_close(self, code, reason=b''): - if isinstance(reason, unicode_type): + if isinstance(reason, str): reason = reason.encode('utf-8') self.write_frame(1, CLOSE, struct.pack(b'!H', code) + reason) @@ -183,7 +182,7 @@ def simple_test(self, server, msgs, expected=(), close_code=NORMAL_CLOSE, send_c expected_messages, expected_controls = [], [] for ex in expected: - if isinstance(ex, unicode_type): + if isinstance(ex, str): ex = TEXT, ex elif isinstance(ex, bytes): ex = BINARY, ex diff --git a/src/calibre/srv/utils.py b/src/calibre/srv/utils.py index 7b85a0286a..abc025750d 100644 --- a/src/calibre/srv/utils.py +++ b/src/calibre/srv/utils.py @@ -19,7 +19,7 @@ from polyglot.builtins import iteritems from polyglot import reprlib from polyglot.http_cookie import SimpleCookie -from polyglot.builtins import unicode_type, as_unicode +from polyglot.builtins import as_unicode from polyglot.urllib import parse_qs, quote as urlquote from polyglot.binary import as_hex_unicode as encode_name, from_hex_unicode as decode_name @@ -30,7 +30,7 @@ def http_date(timeval=None): - return unicode_type(formatdate(timeval=timeval, usegmt=True)) + return str(formatdate(timeval=timeval, usegmt=True)) class MultiDict(dict): # {{{ diff --git a/src/calibre/srv/web_socket.py b/src/calibre/srv/web_socket.py index bddc294529..1f8d6c84a4 100644 --- a/src/calibre/srv/web_socket.py +++ b/src/calibre/srv/web_socket.py @@ -21,7 +21,6 @@ from calibre.utils.speedups import ReadOnlyFileBuffer from polyglot import http_client from polyglot.binary import as_base64_unicode -from polyglot.builtins import unicode_type from polyglot.queue import Empty, Queue HANDSHAKE_STR = ( @@ -178,7 +177,7 @@ def read_payload(self, conn): def create_frame(fin, opcode, payload, mask=None, rsv=0): - if isinstance(payload, unicode_type): + if isinstance(payload, str): payload = payload.encode('utf-8') l = len(payload) header_len = 2 + (0 if l < 126 else 2 if 126 <= l <= 65535 else 8) + (0 if mask is None else 4) @@ -207,7 +206,7 @@ class MessageWriter: def __init__(self, buf, mask=None, chunk_size=None): self.buf, self.data_type, self.mask = buf, BINARY, mask - if isinstance(buf, unicode_type): + if isinstance(buf, str): self.buf, self.data_type = ReadOnlyFileBuffer(buf.encode('utf-8')), TEXT elif isinstance(buf, bytes): self.buf = ReadOnlyFileBuffer(buf) @@ -422,7 +421,7 @@ def ws_control_frame(self, opcode, data): self.set_ws_state() def websocket_close(self, code=NORMAL_CLOSE, reason=b''): - if isinstance(reason, unicode_type): + if isinstance(reason, str): reason = reason.encode('utf-8') self.stop_reading = True reason = reason[:123] @@ -487,7 +486,7 @@ def send_websocket_frame(self, data, is_first=True, is_last=True): ''' Useful for streaming handlers that want to break up messages into frames themselves. Note that these frames will be interleaved with control frames, so they should not be too large. ''' - opcode = (TEXT if isinstance(data, unicode_type) else BINARY) if is_first else CONTINUATION + opcode = (TEXT if isinstance(data, str) else BINARY) if is_first else CONTINUATION fin = 1 if is_last else 0 frame = create_frame(fin, opcode, data) with self.cf_lock: @@ -496,7 +495,7 @@ def send_websocket_frame(self, data, is_first=True, is_last=True): def send_websocket_ping(self, data=b''): ''' Send a PING to the remote client, it should reply with a PONG which will be sent to the handle_websocket_pong callback in your handler. ''' - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') frame = create_frame(True, PING, data) with self.cf_lock: diff --git a/src/calibre/startup.py b/src/calibre/startup.py index 751c984eca..4d5131d66e 100644 --- a/src/calibre/startup.py +++ b/src/calibre/startup.py @@ -10,7 +10,7 @@ import locale, sys, os # Default translation is NOOP -from polyglot.builtins import builtins, unicode_type +from polyglot.builtins import builtins builtins.__dict__['_'] = lambda s: s # For strings which belong in the translation tables, but which shouldn't be @@ -162,7 +162,7 @@ def new_start(self): if name == 'Thread': name = self.name if name: - if isinstance(name, unicode_type): + if isinstance(name, str): name = name.encode('ascii', 'replace').decode('ascii') speedup.set_thread_name(name[:15]) except Exception: diff --git a/src/calibre/test_build.py b/src/calibre/test_build.py index 08414532ef..0d52db5957 100644 --- a/src/calibre/test_build.py +++ b/src/calibre/test_build.py @@ -13,7 +13,7 @@ import os, ctypes, sys, unittest, time, shutil from calibre.constants import iswindows, islinux, ismacos, plugins_loc -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems is_ci = os.environ.get('CI', '').lower() == 'true' is_sanitized = 'libasan' in os.environ.get('LD_PRELOAD', '') @@ -147,7 +147,7 @@ def test_msgpack(self): s = msgpack_dumps(obj) self.assertEqual(obj, msgpack_loads(s)) self.assertEqual(type(msgpack_loads(msgpack_dumps(b'b'))), bytes) - self.assertEqual(type(msgpack_loads(msgpack_dumps('b'))), unicode_type) + self.assertEqual(type(msgpack_loads(msgpack_dumps('b'))), str) large = b'x' * (100 * 1024 * 1024) msgpack_loads(msgpack_dumps(large)) @@ -168,7 +168,7 @@ def test_winutil(self): def au(x, name): self.assertTrue( - isinstance(x, unicode_type), + isinstance(x, str), '%s() did not return a unicode string, instead returning: %r' % (name, x)) for x in 'username temp_path locale_name'.split(): au(getattr(winutil, x)(), x) diff --git a/src/calibre/utils/certgen.py b/src/calibre/utils/certgen.py index e180ddbc72..2b767154ef 100644 --- a/src/calibre/utils/certgen.py +++ b/src/calibre/utils/certgen.py @@ -6,7 +6,6 @@ __copyright__ = '2015, Kovid Goyal ' import socket -from polyglot.builtins import unicode_type from calibre_extensions import certgen @@ -20,7 +19,7 @@ def create_cert_request( organizational_unit=None, email_address=None, alt_names=(), basic_constraints=None ): def enc(x): - if isinstance(x, unicode_type): + if isinstance(x, str): x = x.encode('ascii') return x or None @@ -83,7 +82,7 @@ def create_server_cert( def export(dest, obj, func, *args): if dest is not None: data = func(obj, *args) - if isinstance(data, unicode_type): + if isinstance(data, str): data = data.encode('utf-8') if hasattr(dest, 'write'): dest.write(data) diff --git a/src/calibre/utils/config_base.py b/src/calibre/utils/config_base.py index 0a8374aed4..9b9e1d4172 100644 --- a/src/calibre/utils/config_base.py +++ b/src/calibre/utils/config_base.py @@ -12,7 +12,7 @@ from calibre.utils.lock import ExclusiveFile from calibre.constants import config_dir, CONFIG_DIR_MODE, preferred_encoding, filesystem_encoding, iswindows -from polyglot.builtins import unicode_type, iteritems +from polyglot.builtins import iteritems plugin_dir = os.path.join(config_dir, 'plugins') @@ -21,7 +21,7 @@ def parse_old_style(src): import pickle as cPickle options = {'cPickle':cPickle} try: - if not isinstance(src, unicode_type): + if not isinstance(src, str): src = src.decode('utf-8') src = src.replace('PyQt%d.QtCore' % 4, 'PyQt5.QtCore') src = re.sub(r'cPickle\.loads\(([\'"])', r'cPickle.loads(b\1', src) @@ -295,7 +295,7 @@ def get_override_section(self, src): def parse_string(self, src): options = {} if src: - is_old_style = (isinstance(src, bytes) and src.startswith(b'#')) or (isinstance(src, unicode_type) and src.startswith(u'#')) + is_old_style = (isinstance(src, bytes) and src.startswith(b'#')) or (isinstance(src, str) and src.startswith(u'#')) if is_old_style: options = parse_old_style(src) else: @@ -399,7 +399,7 @@ def set(self, name, val): src = self.option_set.serialize(opts) f.seek(0) f.truncate() - if isinstance(src, unicode_type): + if isinstance(src, str): src = src.encode('utf-8') f.write(src) @@ -550,7 +550,7 @@ def create_global_prefs(conf_obj=None): prefs = ConfigProxy(create_global_prefs()) if prefs['installation_uuid'] is None: import uuid - prefs['installation_uuid'] = unicode_type(uuid.uuid4()) + prefs['installation_uuid'] = str(uuid.uuid4()) # Read tweaks diff --git a/src/calibre/utils/date.py b/src/calibre/utils/date.py index 8b7492e8f5..951386849e 100644 --- a/src/calibre/utils/date.py +++ b/src/calibre/utils/date.py @@ -14,7 +14,7 @@ from calibre.constants import iswindows, ismacos, preferred_encoding from calibre.utils.iso8601 import utc_tz, local_tz, UNDEFINED_DATE from calibre.utils.localization import lcdata -from polyglot.builtins import unicode_type, native_string_type +from polyglot.builtins import native_string_type _utc_tz = utc_tz _local_tz = local_tz @@ -192,13 +192,13 @@ def fromordinal(day, as_utc=True): def isoformat(date_time, assume_utc=False, as_utc=True, sep='T'): if not hasattr(date_time, 'tzinfo'): - return unicode_type(date_time.isoformat()) + return str(date_time.isoformat()) if date_time.tzinfo is None: date_time = date_time.replace(tzinfo=_utc_tz if assume_utc else _local_tz) date_time = date_time.astimezone(_utc_tz if as_utc else _local_tz) # native_string_type(sep) because isoformat barfs with unicode sep on python 2.x - return unicode_type(date_time.isoformat(native_string_type(sep))) + return str(date_time.isoformat(native_string_type(sep))) def internal_iso_format_string(): @@ -211,7 +211,7 @@ def w3cdtf(date_time, assume_utc=False): date_time = date_time.replace(tzinfo=_utc_tz if assume_utc else _local_tz) date_time = date_time.astimezone(_utc_tz if as_utc else _local_tz) - return unicode_type(date_time.strftime('%Y-%m-%dT%H:%M:%SZ')) + return str(date_time.strftime('%Y-%m-%dT%H:%M:%SZ')) def as_local_time(date_time, assume_utc=True): diff --git a/src/calibre/utils/exim.py b/src/calibre/utils/exim.py index b890962283..3492ed17e2 100644 --- a/src/calibre/utils/exim.py +++ b/src/calibre/utils/exim.py @@ -11,7 +11,7 @@ from calibre.utils.config_base import prefs, StringConfig, create_global_prefs from calibre.utils.config import JSONConfig from calibre.utils.filenames import samefile -from polyglot.builtins import iteritems, error_message, unicode_type +from polyglot.builtins import iteritems, error_message from polyglot.binary import as_hex_unicode @@ -25,7 +25,7 @@ def send_file(from_obj, to_obj, chunksize=1<<20): break m.update(raw) to_obj.write(raw) - return unicode_type(m.hexdigest()) + return str(m.hexdigest()) class FileDest: @@ -55,7 +55,7 @@ def flush(self): def close(self): if not self._discard: size = self.exporter.f.tell() - self.start_pos - digest = unicode_type(self.hasher.hexdigest()) + digest = str(self.hasher.hexdigest()) self.exporter.file_metadata[self.key] = (len(self.exporter.parts), self.start_pos, size, digest, self.mtime) del self.exporter, self.hasher @@ -306,7 +306,7 @@ def export_config(self, base_dir, library_usage_stats): except Exception: lpath = None c = create_global_prefs(StringConfig(raw, 'calibre wide preferences')) - c.set('installation_uuid', unicode_type(uuid.uuid4())) + c.set('installation_uuid', str(uuid.uuid4())) c.set('library_path', lpath) raw = c.src if not isinstance(raw, bytes): diff --git a/src/calibre/utils/filenames.py b/src/calibre/utils/filenames.py index 252ecbd6fd..ba934e3d81 100644 --- a/src/calibre/utils/filenames.py +++ b/src/calibre/utils/filenames.py @@ -16,7 +16,7 @@ filesystem_encoding, iswindows, preferred_encoding, ismacos ) from calibre.utils.localization import get_udc -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues def ascii_text(orig): @@ -24,7 +24,7 @@ def ascii_text(orig): try: ascii = udc.decode(orig) except Exception: - if isinstance(orig, unicode_type): + if isinstance(orig, str): orig = orig.encode('ascii', 'replace') ascii = orig.decode(preferred_encoding, 'replace') if isinstance(ascii, bytes): diff --git a/src/calibre/utils/fonts/free_type.py b/src/calibre/utils/fonts/free_type.py index 0ef640c95c..9c85a9fb5e 100644 --- a/src/calibre/utils/fonts/free_type.py +++ b/src/calibre/utils/fonts/free_type.py @@ -10,7 +10,6 @@ from functools import wraps from calibre_extensions.freetype import FreeType as _FreeType -from polyglot.builtins import unicode_type class ThreadingViolation(Exception): @@ -48,7 +47,7 @@ def supports_text(self, text, has_non_printable_chars=True): ''' Returns True if all the characters in text have glyphs in this font. ''' - if not isinstance(text, unicode_type): + if not isinstance(text, str): raise TypeError('%r is not a unicode object'%text) if has_non_printable_chars: from calibre.utils.fonts.utils import get_printable_characters @@ -58,7 +57,7 @@ def supports_text(self, text, has_non_printable_chars=True): @same_thread def glyph_ids(self, text): - if not isinstance(text, unicode_type): + if not isinstance(text, str): raise TypeError('%r is not a unicode object'%text) for char in text: yield self.face.glyph_id(ord(char)) diff --git a/src/calibre/utils/fonts/metadata.py b/src/calibre/utils/fonts/metadata.py index 091f67b845..b818206183 100644 --- a/src/calibre/utils/fonts/metadata.py +++ b/src/calibre/utils/fonts/metadata.py @@ -11,7 +11,6 @@ from collections import namedtuple from calibre.utils.fonts.utils import get_font_names2, get_font_characteristics -from polyglot.builtins import unicode_type class UnsupportedFont(ValueError): @@ -48,7 +47,7 @@ def __init__(self, bytes_or_stream): elif wt == 700: wt = 'bold' else: - wt = unicode_type(wt) + wt = str(wt) self.font_weight = wt self.font_stretch = ('ultra-condensed', 'extra-condensed', diff --git a/src/calibre/utils/fonts/scanner.py b/src/calibre/utils/fonts/scanner.py index 9f693707dd..bbefd8b357 100644 --- a/src/calibre/utils/fonts/scanner.py +++ b/src/calibre/utils/fonts/scanner.py @@ -15,7 +15,7 @@ isworker, filesystem_encoding) from calibre.utils.fonts.metadata import FontMetadata, UnsupportedFont from calibre.utils.icu import sort_key -from polyglot.builtins import itervalues, unicode_type +from polyglot.builtins import itervalues class NoFonts(ValueError): @@ -270,7 +270,7 @@ def find_font_for_text(self, text, allowed_families={'serif', 'sans-serif'}, ''' from calibre.utils.fonts.utils import (supports_text, panose_to_css_generic_family, get_printable_characters) - if not isinstance(text, unicode_type): + if not isinstance(text, str): raise TypeError(u'%r is not unicode'%text) text = get_printable_characters(text) found = {} diff --git a/src/calibre/utils/fonts/sfnt/cff/dict_data.py b/src/calibre/utils/fonts/sfnt/cff/dict_data.py index 66c76630ee..d58d12a391 100644 --- a/src/calibre/utils/fonts/sfnt/cff/dict_data.py +++ b/src/calibre/utils/fonts/sfnt/cff/dict_data.py @@ -7,7 +7,6 @@ __docformat__ = 'restructuredtext en' from struct import pack, unpack_from -from polyglot.builtins import unicode_type t1_operand_encoding = [None] * 256 t1_operand_encoding[0:32] = (32) * ["do_operator"] @@ -71,7 +70,7 @@ def read_real_number(self, b0, data, index): return float(number), index def write_float(self, f, encoding='ignored'): - s = unicode_type(f).upper() + s = str(f).upper() if s[:2] == "0.": s = s[1:] elif s[:3] == "-0.": diff --git a/src/calibre/utils/fonts/sfnt/metrics.py b/src/calibre/utils/fonts/sfnt/metrics.py index 53ccb38288..d68cd52a0d 100644 --- a/src/calibre/utils/fonts/sfnt/metrics.py +++ b/src/calibre/utils/fonts/sfnt/metrics.py @@ -6,7 +6,6 @@ __copyright__ = '2012, Kovid Goyal ' __docformat__ = 'restructuredtext en' -from polyglot.builtins import unicode_type from calibre.utils.fonts.utils import get_all_font_names from calibre.utils.fonts.sfnt.container import UnsupportedFont @@ -94,7 +93,7 @@ def advance_widths(self, string, pixel_size=12.0, stretch=1.0): Return the advance widths (in pixels) for all glyphs corresponding to the characters in string at the specified pixel_size and stretch factor. ''' - if not isinstance(string, unicode_type): + if not isinstance(string, str): raise ValueError('Must supply a unicode object') chars = tuple(map(ord, string)) cmap = self.cmap.get_character_map(chars) diff --git a/src/calibre/utils/fonts/sfnt/subset.py b/src/calibre/utils/fonts/sfnt/subset.py index 368eac9317..9fcdada014 100644 --- a/src/calibre/utils/fonts/sfnt/subset.py +++ b/src/calibre/utils/fonts/sfnt/subset.py @@ -14,7 +14,7 @@ from calibre.utils.icu import safe_chr, ord_string from calibre.utils.fonts.sfnt.container import Sfnt from calibre.utils.fonts.sfnt.errors import UnsupportedFont, NoGlyphs -from polyglot.builtins import unicode_type, iteritems, itervalues +from polyglot.builtins import iteritems, itervalues # TrueType outlines {{{ @@ -109,7 +109,7 @@ def pdf_subset(sfnt, glyphs): def safe_ord(x): - return ord_string(unicode_type(x))[0] + return ord_string(str(x))[0] def subset(raw, individual_chars, ranges=(), warnings=None): @@ -351,12 +351,12 @@ def all(): print('No glyphs!') continue except UnsupportedFont as e: - unsupported.append((font['full_name'], font['path'], unicode_type(e))) + unsupported.append((font['full_name'], font['path'], str(e))) print('Unsupported!') continue except Exception as e: print('Failed!') - failed.append((font['full_name'], font['path'], unicode_type(e))) + failed.append((font['full_name'], font['path'], str(e))) else: averages.append(sum(itervalues(new_stats))/sum(itervalues(old_stats)) * 100) print('Reduced to:', '%.1f'%averages[-1] , '%') diff --git a/src/calibre/utils/fonts/utils.py b/src/calibre/utils/fonts/utils.py index 042411c0f9..3e61d42981 100644 --- a/src/calibre/utils/fonts/utils.py +++ b/src/calibre/utils/fonts/utils.py @@ -10,7 +10,7 @@ from io import BytesIO from collections import defaultdict -from polyglot.builtins import iteritems, itervalues, unicode_type, as_bytes +from polyglot.builtins import iteritems, itervalues, as_bytes class UnsupportedFont(ValueError): @@ -397,7 +397,7 @@ def get_bmp_glyph_ids(table, bmp, codes): def get_glyph_ids(raw, text, raw_is_table=False): - if not isinstance(text, unicode_type): + if not isinstance(text, str): raise TypeError('%r is not a unicode object'%text) if raw_is_table: table = raw @@ -423,7 +423,7 @@ def get_glyph_ids(raw, text, raw_is_table=False): def supports_text(raw, text, has_only_printable_chars=False): - if not isinstance(text, unicode_type): + if not isinstance(text, str): raise TypeError('%r is not a unicode object'%text) if not has_only_printable_chars: text = get_printable_characters(text) diff --git a/src/calibre/utils/fonts/win_fonts.py b/src/calibre/utils/fonts/win_fonts.py index f90aeb88ca..3ad658a7f5 100644 --- a/src/calibre/utils/fonts/win_fonts.py +++ b/src/calibre/utils/fonts/win_fonts.py @@ -13,7 +13,7 @@ from calibre.constants import filesystem_encoding from calibre.utils.fonts.utils import (is_truetype_font, get_font_names, get_font_characteristics) -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class WinFonts: @@ -58,7 +58,7 @@ def get_normalized_name(self, is_italic, weight): return ft def fonts_for_family(self, family, normalize=True): - family = unicode_type(family) + family = str(family) ans = {} for weight, is_italic in product((self.w.FW_NORMAL, self.w.FW_BOLD), (False, True)): if family in self.app_font_families: diff --git a/src/calibre/utils/formatter.py b/src/calibre/utils/formatter.py index bfe34c7e7e..14acf8735c 100644 --- a/src/calibre/utils/formatter.py +++ b/src/calibre/utils/formatter.py @@ -18,7 +18,7 @@ from calibre.ebooks.metadata.book.base import field_metadata from calibre.utils.formatter_functions import formatter_functions from calibre.utils.icu import strcmp -from polyglot.builtins import unicode_type, error_message +from polyglot.builtins import error_message class Node: @@ -906,9 +906,9 @@ def do_node_raw_field(self, prog): else: res = fm['is_multiple']['list_to_ui'].join(res) else: - res = unicode_type(res) + res = str(res) else: - res = unicode_type(res) # Should be the string "None" + res = str(res) # Should be the string "None" if (self.break_reporter): self.break_reporter(prog.node_name, res, prog.line_number) return res @@ -1044,7 +1044,7 @@ def do_node_binary_arithop(self, prog): try: answer = self.ARITHMETIC_BINARY_OPS[prog.operator](float(self.expr(prog.left)), float(self.expr(prog.right))) - res = unicode_type(answer if modf(answer)[0] != 0 else int(answer)) + res = str(answer if modf(answer)[0] != 0 else int(answer)) if (self.break_reporter): self.break_reporter(prog.node_name, res, prog.line_number) return res @@ -1062,7 +1062,7 @@ def do_node_binary_arithop(self, prog): def do_node_unary_arithop(self, prog): try: expr = self.ARITHMETIC_UNARY_OPS[prog.operator](float(self.expr(prog.expr))) - res = unicode_type(expr if modf(expr)[0] != 0 else int(expr)) + res = str(expr if modf(expr)[0] != 0 else int(expr)) if (self.break_reporter): self.break_reporter(prog.node_name, res, prog.line_number) return res @@ -1187,7 +1187,7 @@ def _do_format(self, val, fmt): except: raise ValueError( _('format: type {0} requires a decimal (float) value, got {1}').format(typ, val)) - return unicode_type(('{0:'+fmt+'}').format(val)) + return str(('{0:'+fmt+'}').format(val)) def _explode_format_string(self, fmt): try: @@ -1261,7 +1261,7 @@ def format_field(self, val, fmt): # ensure we are dealing with a string. if isinstance(val, numbers.Number): if val: - val = unicode_type(val) + val = str(val) else: val = '' # Handle conditional text diff --git a/src/calibre/utils/formatter_functions.py b/src/calibre/utils/formatter_functions.py index 368b40d4ab..78dc90fcb6 100644 --- a/src/calibre/utils/formatter_functions.py +++ b/src/calibre/utils/formatter_functions.py @@ -25,7 +25,7 @@ from calibre.utils.icu import capitalize, strcmp, sort_key from calibre.utils.date import parse_date, format_date, now, UNDEFINED_DATE from calibre.utils.localization import calibre_langcode_to_name, canonicalize_lang -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues class FormatterFunctions: @@ -135,12 +135,12 @@ def evaluate(self, formatter, kwargs, mi, locals, *args): def eval_(self, formatter, kwargs, mi, locals, *args): ret = self.evaluate(formatter, kwargs, mi, locals, *args) - if isinstance(ret, (bytes, unicode_type)): + if isinstance(ret, (bytes, str)): return ret if isinstance(ret, list): return ','.join(ret) if isinstance(ret, (numbers.Number, bool)): - return unicode_type(ret) + return str(ret) class BuiltinFormatterFunction(FormatterFunction): @@ -258,7 +258,7 @@ def evaluate(self, formatter, kwargs, mi, locals, *args): for v in args: v = float(v if v and v != 'None' else 0) res += v - return unicode_type(res) + return str(res) class BuiltinSubtract(BuiltinFormatterFunction): @@ -272,7 +272,7 @@ class BuiltinSubtract(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x, y): x = float(x if x and x != 'None' else 0) y = float(y if y and y != 'None' else 0) - return unicode_type(x - y) + return str(x - y) class BuiltinMultiply(BuiltinFormatterFunction): @@ -288,7 +288,7 @@ def evaluate(self, formatter, kwargs, mi, locals, *args): for v in args: v = float(v if v and v != 'None' else 0) res *= v - return unicode_type(res) + return str(res) class BuiltinDivide(BuiltinFormatterFunction): @@ -302,7 +302,7 @@ class BuiltinDivide(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x, y): x = float(x if x and x != 'None' else 0) y = float(y if y and y != 'None' else 0) - return unicode_type(x / y) + return str(x / y) class BuiltinCeiling(BuiltinFormatterFunction): @@ -315,7 +315,7 @@ class BuiltinCeiling(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x): x = float(x if x and x != 'None' else 0) - return unicode_type(int(ceil(x))) + return str(int(ceil(x))) class BuiltinFloor(BuiltinFormatterFunction): @@ -328,7 +328,7 @@ class BuiltinFloor(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x): x = float(x if x and x != 'None' else 0) - return unicode_type(int(floor(x))) + return str(int(floor(x))) class BuiltinRound(BuiltinFormatterFunction): @@ -340,7 +340,7 @@ class BuiltinRound(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x): x = float(x if x and x != 'None' else 0) - return unicode_type(int(round(x))) + return str(int(round(x))) class BuiltinMod(BuiltinFormatterFunction): @@ -353,7 +353,7 @@ class BuiltinMod(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x, y): x = float(x if x and x != 'None' else 0) y = float(y if y and y != 'None' else 0) - return unicode_type(int(x % y)) + return str(int(x % y)) class BuiltinFractionalPart(BuiltinFormatterFunction): @@ -366,7 +366,7 @@ class BuiltinFractionalPart(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals, x): x = float(x if x and x != 'None' else 0) - return unicode_type(modf(x)[0]) + return str(modf(x)[0]) class BuiltinTemplate(BuiltinFormatterFunction): @@ -438,7 +438,7 @@ def evaluate(self, formatter, kwargs, mi, locals, list_val, sep, id_prefix): l = [v.strip() for v in list_val.split(sep)] res = '' for i,v in enumerate(l): - res = locals[id_prefix+'_'+unicode_type(i)] = v + res = locals[id_prefix+'_'+str(i)] = v return res @@ -483,7 +483,7 @@ def evaluate(self, formatter, kwargs, mi, locals, name, default=None): if fm is None: return ', '.join(res) return fm['is_multiple']['list_to_ui'].join(res) - return unicode_type(res) + return str(res) class BuiltinRawList(BuiltinFormatterFunction): @@ -838,7 +838,7 @@ class BuiltinCount(BuiltinFormatterFunction): 'Aliases: count(), list_count()') def evaluate(self, formatter, kwargs, mi, locals, val, sep): - return unicode_type(len([v for v in val.split(sep) if v])) + return str(len([v for v in val.split(sep) if v])) class BuiltinListCountMatching(BuiltinFormatterFunction): @@ -857,7 +857,7 @@ def evaluate(self, formatter, kwargs, mi, locals, list_, pattern, sep): for v in [x.strip() for x in list_.split(sep) if x.strip()]: if re.search(pattern, v, flags=re.I): res += 1 - return unicode_type(res) + return str(res) class BuiltinListitem(BuiltinFormatterFunction): @@ -970,7 +970,7 @@ class BuiltinFormatsSizes(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals): fmt_data = mi.get('format_metadata', {}) try: - return ','.join(k.upper()+':'+unicode_type(v['size']) for k,v in iteritems(fmt_data)) + return ','.join(k.upper()+':'+str(v['size']) for k,v in iteritems(fmt_data)) except: return '' @@ -989,7 +989,7 @@ class BuiltinFormatsPaths(BuiltinFormatterFunction): def evaluate(self, formatter, kwargs, mi, locals): fmt_data = mi.get('format_metadata', {}) try: - return ','.join(k.upper()+':'+unicode_type(v['path']) for k,v in iteritems(fmt_data)) + return ','.join(k.upper()+':'+str(v['path']) for k,v in iteritems(fmt_data)) except: return '' @@ -1231,7 +1231,7 @@ def evaluate(self, formatter, kwargs, mi, locals): try: v = mi._proxy_metadata.book_size if v is not None: - return unicode_type(mi._proxy_metadata.book_size) + return str(mi._proxy_metadata.book_size) return '' except: pass @@ -1270,7 +1270,7 @@ def evaluate(self, formatter, kwargs, mi, locals): with suppress(Exception): from calibre.gui2.ui import get_gui c = get_gui().current_db.new_api.annotation_count_for_book(mi.id) - return '' if c == 0 else unicode_type(c) + return '' if c == 0 else str(c) return _('This function can be used only in the GUI') diff --git a/src/calibre/utils/hyphenation/hyphenate.py b/src/calibre/utils/hyphenation/hyphenate.py index ba1efbe460..87835425e5 100644 --- a/src/calibre/utils/hyphenation/hyphenate.py +++ b/src/calibre/utils/hyphenation/hyphenate.py @@ -10,7 +10,6 @@ from calibre.utils.hyphenation.dictionaries import ( dictionary_name_for_locale, path_to_dictionary ) -from polyglot.builtins import unicode_type from polyglot.functools import lru_cache REGEX_FLAGS = regex.VERSION1 | regex.WORD | regex.FULLCASE | regex.UNICODE @@ -27,7 +26,7 @@ def dictionary_for_locale(locale): def add_soft_hyphens(word, dictionary, hyphen_char='\u00ad'): - word = unicode_type(word) + word = str(word) if len(word) > 99 or '=' in word: return word q = word diff --git a/src/calibre/utils/icu.py b/src/calibre/utils/icu.py index a47c1c00dd..1a52db161a 100644 --- a/src/calibre/utils/icu.py +++ b/src/calibre/utils/icu.py @@ -11,7 +11,7 @@ from calibre.utils.config_base import tweaks from calibre_extensions import icu as _icu -from polyglot.builtins import cmp, unicode_type +from polyglot.builtins import cmp _locale = _collator = _primary_collator = _sort_collator = _numeric_collator = _case_sensitive_collator = None cmp @@ -224,7 +224,7 @@ def capitalize(x): def character_name(string): try: - return _icu.character_name(unicode_type(string)) or None + return _icu.character_name(str(string)) or None except (TypeError, ValueError, KeyError): pass @@ -241,7 +241,7 @@ def normalize(text, mode='NFC'): # that unless you have very good reasons not too. Also, it's speed # decreases on wide python builds, where conversion to/from ICU's string # representation is slower. - return _icu.normalize(_nmodes[mode], unicode_type(text)) + return _icu.normalize(_nmodes[mode], str(text)) def contractions(col=None): diff --git a/src/calibre/utils/icu_test.py b/src/calibre/utils/icu_test.py index 85d259df12..281288e0e9 100644 --- a/src/calibre/utils/icu_test.py +++ b/src/calibre/utils/icu_test.py @@ -9,7 +9,7 @@ from contextlib import contextmanager import calibre.utils.icu as icu -from polyglot.builtins import iteritems, unicode_type, cmp +from polyglot.builtins import iteritems, cmp @contextmanager @@ -164,7 +164,7 @@ def test_break_iterator(self): ' Test the break iterator ' from calibre.spell.break_iterator import split_into_words as split, index_of, split_into_words_and_positions, count_words for q in ('one two three', ' one two three', 'one\ntwo three ', ): - self.ae(split(unicode_type(q)), ['one', 'two', 'three'], 'Failed to split: %r' % q) + self.ae(split(str(q)), ['one', 'two', 'three'], 'Failed to split: %r' % q) self.ae(split(u'I I\'m'), ['I', "I'm"]) self.ae(split(u'out-of-the-box'), ['out-of-the-box']) self.ae(split(u'-one two-'), ['-one', 'two-']) diff --git a/src/calibre/utils/img.py b/src/calibre/utils/img.py index ca73002aca..e97c22d316 100644 --- a/src/calibre/utils/img.py +++ b/src/calibre/utils/img.py @@ -23,7 +23,7 @@ from calibre.utils.filenames import atomic_rename from calibre.utils.imghdr import what from calibre_extensions import imageops -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes # Utilities {{{ @@ -133,7 +133,7 @@ def image_from_path(path): def image_from_x(x): ' Create an image from a bytestring or a path or a file like object. ' - if isinstance(x, unicode_type): + if isinstance(x, str): return image_from_path(x) if hasattr(x, 'read'): return image_from_data(x.read()) @@ -606,7 +606,7 @@ def encode_jpeg(file_path, quality=80): from calibre.utils.speedups import ReadOnlyFileBuffer quality = max(0, min(100, int(quality))) exe = get_exe_path('cjpeg') - cmd = [exe] + '-optimize -progressive -maxmemory 100M -quality'.split() + [unicode_type(quality)] + cmd = [exe] + '-optimize -progressive -maxmemory 100M -quality'.split() + [str(quality)] img = QImage() if not img.load(file_path): raise ValueError('%s is not a valid image file' % file_path) diff --git a/src/calibre/utils/imghdr.py b/src/calibre/utils/imghdr.py index 2b806a60a9..d3aed07480 100644 --- a/src/calibre/utils/imghdr.py +++ b/src/calibre/utils/imghdr.py @@ -6,7 +6,7 @@ from struct import unpack, error import os from calibre.utils.speedups import ReadOnlyFileBuffer -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes """ Recognize image file formats and sizes based on their first few bytes.""" @@ -42,7 +42,7 @@ def identify(src): recognized. ''' needs_close = False - if isinstance(src, unicode_type): + if isinstance(src, str): stream = lopen(src, 'rb') needs_close = True elif isinstance(src, bytes): diff --git a/src/calibre/utils/ipc/simple_worker.py b/src/calibre/utils/ipc/simple_worker.py index c44facfa0e..1cc36aa8a5 100644 --- a/src/calibre/utils/ipc/simple_worker.py +++ b/src/calibre/utils/ipc/simple_worker.py @@ -17,7 +17,7 @@ from calibre.utils.ipc import eintr_retry_call from calibre.utils.ipc.launch import Worker from calibre.utils.monotonic import monotonic -from polyglot.builtins import environ_item, string_or_bytes, unicode_type +from polyglot.builtins import environ_item, string_or_bytes if iswindows: from multiprocessing.connection import PipeConnection as Connection @@ -268,7 +268,7 @@ def offload_worker(env={}, priority='normal', cwd=None): def compile_code(src): import io import re - if not isinstance(src, unicode_type): + if not isinstance(src, str): match = re.search(br'coding[:=]\s*([-\w.]+)', src[:200]) enc = match.group(1).decode('utf-8') if match else 'utf-8' src = src.decode(enc) diff --git a/src/calibre/utils/linux_trash.py b/src/calibre/utils/linux_trash.py index 13bf248b80..7ff880ba3f 100644 --- a/src/calibre/utils/linux_trash.py +++ b/src/calibre/utils/linux_trash.py @@ -23,7 +23,6 @@ from datetime import datetime import shutil -from polyglot.builtins import unicode_type from polyglot.urllib import quote FILES_DIR = 'files' @@ -40,9 +39,9 @@ def uniquote(raw): - if isinstance(raw, unicode_type): + if isinstance(raw, str): raw = raw.encode('utf-8') - return unicode_type(quote(raw)) + return str(quote(raw)) def is_parent(parent, path): @@ -120,7 +119,7 @@ def find_ext_volume_global_trash(volume_root): if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX): return None - trash_dir = op.join(trash_dir, unicode_type(uid)) + trash_dir = op.join(trash_dir, str(uid)) try: check_create(trash_dir) except OSError: diff --git a/src/calibre/utils/localization.py b/src/calibre/utils/localization.py index e59ba0994b..de9c4a3f4c 100644 --- a/src/calibre/utils/localization.py +++ b/src/calibre/utils/localization.py @@ -9,7 +9,7 @@ import os, locale, re, io from gettext import GNUTranslations, NullTranslations -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems _available_translations = None @@ -430,7 +430,7 @@ def calibre_langcode_to_name(lc, localize=True): def canonicalize_lang(raw): if not raw: return None - if not isinstance(raw, unicode_type): + if not isinstance(raw, str): raw = raw.decode('utf-8', 'ignore') raw = raw.lower().strip() if not raw: diff --git a/src/calibre/utils/magick/__init__.py b/src/calibre/utils/magick/__init__.py index dcf0f69273..1f52c56bcf 100644 --- a/src/calibre/utils/magick/__init__.py +++ b/src/calibre/utils/magick/__init__.py @@ -7,7 +7,6 @@ __docformat__ = 'restructuredtext en' from calibre.utils.magick.legacy import Image, PixelWand -from polyglot.builtins import unicode_type if False: PixelWand @@ -15,5 +14,5 @@ def create_canvas(width, height, bgcolor='#ffffff'): canvas = Image() - canvas.create_canvas(int(width), int(height), unicode_type(bgcolor)) + canvas.create_canvas(int(width), int(height), str(bgcolor)) return canvas diff --git a/src/calibre/utils/matcher.py b/src/calibre/utils/matcher.py index ca8e16d142..0548162723 100644 --- a/src/calibre/utils/matcher.py +++ b/src/calibre/utils/matcher.py @@ -16,7 +16,7 @@ from calibre import detect_ncpus as cpu_count, as_unicode from calibre.constants import filesystem_encoding from calibre.utils.icu import primary_sort_key, primary_find, primary_collator -from polyglot.builtins import iteritems, itervalues, unicode_type +from polyglot.builtins import iteritems, itervalues from polyglot.queue import Queue DEFAULT_LEVEL1 = '/' @@ -95,7 +95,7 @@ def __init__( w = [Worker(requests, results) for i in range(max(1, cpu_count()))] [x.start() for x in w] workers.extend(w) - items = map(lambda x: normalize('NFC', unicode_type(x)), filter(None, items)) + items = map(lambda x: normalize('NFC', str(x)), filter(None, items)) self.items = items = tuple(items) tasks = split(items, len(workers)) self.task_maps = [{j: i for j, (i, _) in enumerate(task)} for task in tasks] @@ -106,7 +106,7 @@ def __init__( self.sort_keys = None def __call__(self, query, limit=None): - query = normalize('NFC', unicode_type(query)) + query = normalize('NFC', str(query)) with wlock: for i, scorer in enumerate(self.scorers): workers[0].requests.put((i, scorer, query)) @@ -259,7 +259,7 @@ def __init__( self.m = Matcher( items, primary_collator().capsule, - unicode_type(level1), unicode_type(level2), unicode_type(level3) + str(level1), str(level2), str(level3) ) def __call__(self, query): @@ -292,12 +292,12 @@ def doit(c): start = memory() for i in range(10): - doit(unicode_type(i)) + doit(str(i)) gc.collect() used10 = memory() - start start = memory() for i in range(100): - doit(unicode_type(i)) + doit(str(i)) gc.collect() used100 = memory() - start if used100 > 0 and used10 > 0: diff --git a/src/calibre/utils/podofo/__init__.py b/src/calibre/utils/podofo/__init__.py index 306a53eca3..9250796b6b 100644 --- a/src/calibre/utils/podofo/__init__.py +++ b/src/calibre/utils/podofo/__init__.py @@ -11,7 +11,6 @@ from calibre.ebooks.metadata import authors_to_string from calibre.ptempfile import TemporaryDirectory from calibre.utils.ipc.simple_worker import WorkerError, fork_job -from polyglot.builtins import unicode_type def get_podofo(): @@ -22,7 +21,7 @@ def get_podofo(): def prep(val): if not val: return '' - if not isinstance(val, unicode_type): + if not isinstance(val, str): val = val.decode(preferred_encoding, 'replace') return val.strip() diff --git a/src/calibre/utils/rapydscript.py b/src/calibre/utils/rapydscript.py index 7a27389fa0..7c2e44344e 100644 --- a/src/calibre/utils/rapydscript.py +++ b/src/calibre/utils/rapydscript.py @@ -17,7 +17,7 @@ ) from calibre.ptempfile import TemporaryDirectory from calibre.utils.filenames import atomic_rename -from polyglot.builtins import as_bytes, as_unicode, exec_path, unicode_type +from polyglot.builtins import as_bytes, as_unicode, exec_path COMPILER_PATH = 'rapydscript/compiler.js.xz' special_title = '__webengine_messages_pending__' @@ -475,7 +475,7 @@ def compile_srv(): rapydscript_dir = os.path.join(base, 'src', 'pyj') rb = os.path.join(base, 'src', 'calibre', 'srv', 'render_book.py') with lopen(rb, 'rb') as f: - rv = unicode_type(int(re.search(br'^RENDER_VERSION\s+=\s+(\d+)', f.read(), re.M).group(1))) + rv = str(int(re.search(br'^RENDER_VERSION\s+=\s+(\d+)', f.read(), re.M).group(1))) mathjax_version = json.loads(P('mathjax/manifest.json', data=True, allow_user_override=False))['etag'] base = os.path.join(base, 'resources', 'content-server') fname = os.path.join(rapydscript_dir, 'srv.pyj') diff --git a/src/calibre/utils/recycle_bin.py b/src/calibre/utils/recycle_bin.py index ed28767b18..caaece8adf 100644 --- a/src/calibre/utils/recycle_bin.py +++ b/src/calibre/utils/recycle_bin.py @@ -11,7 +11,6 @@ from calibre import isbytestring from calibre.constants import (iswindows, ismacos, filesystem_encoding, islinux) -from polyglot.builtins import unicode_type recycle = None @@ -29,7 +28,7 @@ def start_recycler(): recycler = start_pipe_worker('from calibre.utils.recycle_bin import recycler_main; recycler_main()') def recycle_path(path): - winutil.move_to_trash(unicode_type(path)) + winutil.move_to_trash(str(path)) def recycler_main(): stdin = getattr(sys.stdin, 'buffer', sys.stdin) diff --git a/src/calibre/utils/search_query_parser.py b/src/calibre/utils/search_query_parser.py index 890f71049d..56e8cdb014 100644 --- a/src/calibre/utils/search_query_parser.py +++ b/src/calibre/utils/search_query_parser.py @@ -23,7 +23,7 @@ from calibre.constants import preferred_encoding from calibre.utils.icu import sort_key from calibre import prints -from polyglot.builtins import codepoint_to_chr, unicode_type +from polyglot.builtins import codepoint_to_chr ''' @@ -57,7 +57,7 @@ def save_queries(self): db.set_pref(self.opt_name, self.queries) def force_unicode(self, x): - if not isinstance(x, unicode_type): + if not isinstance(x, str): x = x.decode(preferred_encoding, 'replace') return x @@ -154,8 +154,8 @@ def __init__(self): # Had to translate named constants to numeric values lex_scanner = re.Scanner([ (r'[()]', lambda x,t: (Parser.OPCODE, t)), - (r'@.+?:[^")\s]+', lambda x,t: (Parser.WORD, unicode_type(t))), - (r'[^"()\s]+', lambda x,t: (Parser.WORD, unicode_type(t))), + (r'@.+?:[^")\s]+', lambda x,t: (Parser.WORD, str(t))), + (r'[^"()\s]+', lambda x,t: (Parser.WORD, str(t))), (r'".*?((? -from polyglot.builtins import unicode_type - MSGPACK_MIME = 'application/x-msgpack' CANARY = 'jPoAv3zOyHvQ5JFNYg4hJ9' @@ -24,7 +22,7 @@ def create_encoder(for_json=False): def encoder(obj): if isinstance(obj, datetime): - return encoded(0, unicode_type(obj.isoformat()), ExtType) + return encoded(0, str(obj.isoformat()), ExtType) if isinstance(obj, (set, frozenset)): return encoded(1, tuple(obj), ExtType) if getattr(obj, '__calibre_serializable__', False): diff --git a/src/calibre/utils/short_uuid.py b/src/calibre/utils/short_uuid.py index d7b3a2ca0b..63b1e0fe16 100644 --- a/src/calibre/utils/short_uuid.py +++ b/src/calibre/utils/short_uuid.py @@ -9,8 +9,6 @@ import string, math, uuid as _uuid -from polyglot.builtins import unicode_type - def num_to_string(number, alphabet, alphabet_len, pad_to_length=None): ans = [] @@ -36,7 +34,7 @@ def __init__(self, alphabet=None): # We do not include zero and one in the default alphabet as they can be # confused with the letters O and I in some fonts. And removing them # does not change the uuid_pad_len. - self.alphabet = tuple(sorted(unicode_type(alphabet or (string.digits + string.ascii_letters)[2:]))) + self.alphabet = tuple(sorted(str(alphabet or (string.digits + string.ascii_letters)[2:]))) self.alphabet_len = len(self.alphabet) self.alphabet_map = {c:i for i, c in enumerate(self.alphabet)} self.uuid_pad_len = int(math.ceil(math.log(1 << 128, self.alphabet_len))) diff --git a/src/calibre/utils/smtp.py b/src/calibre/utils/smtp.py index db11b5a523..b63fc3856d 100644 --- a/src/calibre/utils/smtp.py +++ b/src/calibre/utils/smtp.py @@ -13,7 +13,7 @@ import sys, traceback, os, socket, encodings.idna as idna from calibre import isbytestring from calibre.constants import iswindows -from polyglot.builtins import unicode_type, as_unicode, native_string_type +from polyglot.builtins import as_unicode, native_string_type def decode_fqdn(fqdn): @@ -112,7 +112,7 @@ def get_mx(host, verbose=0): print('Find mail exchanger for', host) answers = list(dns.resolver.query(host, 'MX')) answers.sort(key=lambda x: int(getattr(x, 'preference', sys.maxsize))) - return [unicode_type(x.exchange) for x in answers if hasattr(x, 'exchange')] + return [str(x.exchange) for x in answers if hasattr(x, 'exchange')] def sendmail_direct(from_, to, msg, timeout, localhost, verbose, diff --git a/src/calibre/utils/smtplib.py b/src/calibre/utils/smtplib.py index 437519b8ac..2fce3da7b1 100644 --- a/src/calibre/utils/smtplib.py +++ b/src/calibre/utils/smtplib.py @@ -52,7 +52,7 @@ from sys import stderr from functools import partial -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes __all__ = ["SMTPException", "SMTPServerDisconnected", "SMTPResponseException", "SMTPSenderRefused", "SMTPRecipientsRefused", "SMTPDataError", @@ -590,7 +590,7 @@ def login(self, user, password): def encode_cram_md5(challenge, user, password): challenge = base64.decodestring(challenge) - if isinstance(password, unicode_type): # Added by Kovid, see http://bugs.python.org/issue5285 + if isinstance(password, str): # Added by Kovid, see http://bugs.python.org/issue5285 password = password.encode('utf-8') response = user + " " + hmac.HMAC(password, challenge).hexdigest() return encode_base64(response, eol="") diff --git a/src/calibre/utils/titlecase.py b/src/calibre/utils/titlecase.py index 04544a4dcd..fe76280d26 100644 --- a/src/calibre/utils/titlecase.py +++ b/src/calibre/utils/titlecase.py @@ -12,7 +12,6 @@ import re from calibre.utils.icu import capitalize, upper -from polyglot.builtins import unicode_type __all__ = ['titlecase'] __version__ = '0.5' @@ -23,7 +22,7 @@ SMALL_WORDS = re.compile(r'^(%s)$' % SMALL, re.I) INLINE_PERIOD = re.compile(r'[a-z][.][a-z]', re.I) UC_ELSEWHERE = re.compile(r'[%s]*?[a-zA-Z]+[A-Z]+?' % PUNCT) -CAPFIRST = re.compile(unicode_type(r"^[%s]*?(\w)" % PUNCT), flags=re.UNICODE) +CAPFIRST = re.compile(str(r"^[%s]*?(\w)" % PUNCT), flags=re.UNICODE) SMALL_FIRST = re.compile(r'^([%s]*)(%s)\b' % (PUNCT, SMALL), re.I|re.U) SMALL_LAST = re.compile(r'\b(%s)[%s]?$' % (SMALL, PUNCT), re.I|re.U) SMALL_AFTER_NUM = re.compile(r'(\d+\s+)(a|an|the)\b', re.I|re.U) diff --git a/src/calibre/utils/windows/wintest.py b/src/calibre/utils/windows/wintest.py index 8562fb67c7..e3735739fb 100644 --- a/src/calibre/utils/windows/wintest.py +++ b/src/calibre/utils/windows/wintest.py @@ -5,7 +5,6 @@ import os import unittest -from polyglot.builtins import unicode_type class TestWinutil(unittest.TestCase): @@ -18,7 +17,7 @@ def tearDown(self): del self.winutil def test_add_to_recent_docs(self): - path = unicode_type(os.path.abspath(__file__)) + path = str(os.path.abspath(__file__)) self.winutil.add_to_recent_docs(path, None) self.winutil.add_to_recent_docs(path, 'some-app-uid') diff --git a/src/calibre/utils/winreg/lib.py b/src/calibre/utils/winreg/lib.py index 4c9b808160..53a30a7fa0 100644 --- a/src/calibre/utils/winreg/lib.py +++ b/src/calibre/utils/winreg/lib.py @@ -7,7 +7,6 @@ import ctypes, ctypes.wintypes as types, struct, datetime, numbers -from polyglot.builtins import unicode_type from calibre_extensions import winutil try: @@ -113,11 +112,11 @@ def expand_environment_strings(src): def convert_to_registry_data(value, has_expansions=False): if value is None: return None, winreg.REG_NONE, 0 - if isinstance(value, (unicode_type, bytes)): + if isinstance(value, (str, bytes)): buf = ctypes.create_unicode_buffer(value) return buf, (winreg.REG_EXPAND_SZ if has_expansions else winreg.REG_SZ), len(buf) * 2 if isinstance(value, (list, tuple)): - buf = ctypes.create_unicode_buffer('\0'.join(map(unicode_type, value)) + '\0\0') + buf = ctypes.create_unicode_buffer('\0'.join(map(str, value)) + '\0\0') return buf, winreg.REG_MULTI_SZ, len(buf) * 2 if isinstance(value, numbers.Integral): try: diff --git a/src/calibre/utils/zipfile.py b/src/calibre/utils/zipfile.py index 149ddb7c7a..53391854ad 100644 --- a/src/calibre/utils/zipfile.py +++ b/src/calibre/utils/zipfile.py @@ -18,7 +18,7 @@ from calibre.constants import filesystem_encoding from calibre.ebooks.chardet import detect from calibre.ptempfile import SpooledTemporaryFile -from polyglot.builtins import string_or_bytes, unicode_type, as_bytes +from polyglot.builtins import string_or_bytes, as_bytes try: import zlib # We may need its compression method @@ -155,7 +155,7 @@ class LargeZipFile(Exception): def decode_arcname(name): - if not isinstance(name, unicode_type): + if not isinstance(name, str): try: name = name.decode('utf-8') except Exception: @@ -407,7 +407,7 @@ def FileHeader(self): return header + filename + extra def _encodeFilenameFlags(self): - if isinstance(self.filename, unicode_type): + if isinstance(self.filename, str): return self.filename.encode('utf-8'), self.flag_bits | 0x800 else: return self.filename, self.flag_bits @@ -1224,7 +1224,7 @@ def write(self, filename, arcname=None, compress_type=None): arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] - if not isinstance(arcname, unicode_type): + if not isinstance(arcname, str): arcname = arcname.decode(filesystem_encoding) if isdir and not arcname.endswith('/'): arcname += '/' @@ -1302,7 +1302,7 @@ def writestr(self, zinfo_or_arcname, byts, permissions=0o600, if not isinstance(byts, bytes): byts = byts.encode('utf-8') if not isinstance(zinfo_or_arcname, ZipInfo): - if not isinstance(zinfo_or_arcname, unicode_type): + if not isinstance(zinfo_or_arcname, str): zinfo_or_arcname = zinfo_or_arcname.decode(filesystem_encoding) zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())[:6]) @@ -1506,7 +1506,7 @@ def rbytes(name): with SpooledTemporaryFile(max_size=100*1024*1024) as temp: ztemp = ZipFile(temp, 'w') for obj in z.infolist(): - if isinstance(obj.filename, unicode_type): + if isinstance(obj.filename, str): obj.flag_bits |= 0x16 # Set isUTF-8 bit if obj.filename in names: ztemp.writestr(obj, rbytes(obj.filename)) diff --git a/src/calibre/web/feeds/__init__.py b/src/calibre/web/feeds/__init__.py index ebdedaf3e7..cec8c7aefb 100644 --- a/src/calibre/web/feeds/__init__.py +++ b/src/calibre/web/feeds/__init__.py @@ -12,7 +12,7 @@ from calibre import entity_to_unicode, strftime, force_unicode from calibre.utils.date import dt_factory, utcnow, local_tz from calibre.utils.cleantext import clean_ascii_chars, clean_xml_chars -from polyglot.builtins import unicode_type, string_or_bytes +from polyglot.builtins import string_or_bytes class Article: @@ -35,9 +35,9 @@ def __init__(self, id, title, url, author, summary, published, content): self.author = author self.toc_thumbnail = None self.internal_toc_entries = () - if author and not isinstance(author, unicode_type): + if author and not isinstance(author, str): author = author.decode('utf-8', 'replace') - if summary and not isinstance(summary, unicode_type): + if summary and not isinstance(summary, str): summary = summary.decode('utf-8', 'replace') summary = clean_xml_chars(summary) if summary else summary self.summary = summary @@ -68,13 +68,13 @@ def formatted_date(self): @formatted_date.setter def formatted_date(self, val): - if isinstance(val, unicode_type): + if isinstance(val, str): self._formatted_date = val @property def title(self): t = self._title - if not isinstance(t, unicode_type) and hasattr(t, 'decode'): + if not isinstance(t, str) and hasattr(t, 'decode'): t = t.decode('utf-8', 'replace') return t @@ -142,7 +142,7 @@ def populate_from_feed(self, feed, title=None, oldest_article=7, def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): - self.title = unicode_type(title if title else _('Unknown feed')) + self.title = str(title if title else _('Unknown feed')) self.description = '' self.image_url = None self.articles = [] @@ -209,7 +209,7 @@ def parse_article(self, item): author = item.get('author', None) content = [i.value for i in item.get('content', []) if i.value] - content = [i if isinstance(i, unicode_type) else i.decode('utf-8', 'replace') + content = [i if isinstance(i, str) else i.decode('utf-8', 'replace') for i in content] content = '\n'.join(content) if not content.strip(): @@ -225,7 +225,7 @@ def parse_article(self, item): self.logger.debug('Skipping article %s (%s) from feed %s as it is too old.'% (title, article.localtime.strftime('%a, %d %b, %Y %H:%M'), self.title)) except UnicodeDecodeError: - if not isinstance(title, unicode_type): + if not isinstance(title, str): title = title.decode('utf-8', 'replace') self.logger.debug('Skipping article %s as it is too old'%title) diff --git a/src/calibre/web/feeds/news.py b/src/calibre/web/feeds/news.py index 21e760cddf..915d4d1e46 100644 --- a/src/calibre/web/feeds/news.py +++ b/src/calibre/web/feeds/news.py @@ -38,7 +38,7 @@ AbortArticle, RecursiveFetcher, option_parser as web2disk_option_parser ) from calibre.web.fetch.utils import prepare_masthead_image -from polyglot.builtins import string_or_bytes, unicode_type +from polyglot.builtins import string_or_bytes def classes(classes): @@ -712,7 +712,7 @@ def index_to_soup(self, url_or_raw, raw=False, as_tree=False, save_raw=None): _raw = url_or_raw if raw: return _raw - if not isinstance(_raw, unicode_type) and self.encoding: + if not isinstance(_raw, str) and self.encoding: if callable(self.encoding): _raw = self.encoding(_raw) else: @@ -721,7 +721,7 @@ def index_to_soup(self, url_or_raw, raw=False, as_tree=False, save_raw=None): strip_encoding_declarations, xml_to_unicode ) from calibre.utils.cleantext import clean_xml_chars - if isinstance(_raw, unicode_type): + if isinstance(_raw, str): _raw = strip_encoding_declarations(_raw) else: _raw = xml_to_unicode(_raw, strip_encoding_pats=True, resolve_entities=True)[0] @@ -898,8 +898,8 @@ def __init__(self, options, log, progress_reporter): :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string message. The message should be optional. ''' self.log = ThreadSafeWrapper(log) - if not isinstance(self.title, unicode_type): - self.title = unicode_type(self.title, 'utf-8', 'replace') + if not isinstance(self.title, str): + self.title = str(self.title, 'utf-8', 'replace') self.debug = options.verbose > 1 self.output_dir = os.path.abspath(os.getcwd()) @@ -934,9 +934,9 @@ def __init__(self, options, log, progress_reporter): self.css_map = {} web2disk_cmdline = ['web2disk', - '--timeout', unicode_type(self.timeout), - '--max-recursions', unicode_type(self.recursions), - '--delay', unicode_type(self.delay), + '--timeout', str(self.timeout), + '--max-recursions', str(self.recursions), + '--delay', str(self.delay), ] if self.verbose: @@ -1429,7 +1429,7 @@ def default_cover(self, cover_file): ''' try: from calibre.ebooks.covers import create_cover - title = self.title if isinstance(self.title, unicode_type) else \ + title = self.title if isinstance(self.title, str) else \ self.title.decode(preferred_encoding, 'replace') date = strftime(self.timefmt).replace('[', '').replace(']', '') img_data = create_cover(title, [date]) @@ -1478,7 +1478,7 @@ def create_opf(self, feeds, dir=None): article_titles.append(force_unicode(a.title, 'utf-8')) desc = self.description - if not isinstance(desc, unicode_type): + if not isinstance(desc, str): desc = desc.decode('utf-8', 'replace') mi.comments = (_('Articles in this issue:' ) + '\n\n' + '\n\n'.join(article_titles)) + '\n\n' + desc @@ -1589,7 +1589,7 @@ def feed_index(num, parent): elem = BeautifulSoup(templ.render(doctype='xhtml').decode('utf-8')).find('div') body.insert(len(body.contents), elem) with open(last, 'wb') as fi: - fi.write(unicode_type(soup).encode('utf-8')) + fi.write(str(soup).encode('utf-8')) if len(feeds) == 0: raise Exception('All feeds are empty, aborting.') diff --git a/src/calibre/web/feeds/recipes/__init__.py b/src/calibre/web/feeds/recipes/__init__.py index 9ffcb3d74b..5e16423832 100644 --- a/src/calibre/web/feeds/recipes/__init__.py +++ b/src/calibre/web/feeds/recipes/__init__.py @@ -10,7 +10,7 @@ AutomaticNewsRecipe, CalibrePeriodical) from calibre.ebooks.BeautifulSoup import BeautifulSoup from calibre.utils.config import JSONConfig -from polyglot.builtins import itervalues, unicode_type, codepoint_to_chr +from polyglot.builtins import itervalues, codepoint_to_chr basic_recipes = (BasicNewsRecipe, AutomaticNewsRecipe, CustomIndexRecipe, CalibrePeriodical) @@ -32,7 +32,7 @@ def compile_recipe(src): :return: Recipe class or None, if no such class was found in src ''' - if not isinstance(src, unicode_type): + if not isinstance(src, str): match = re.search(br'coding[:=]\s*([-\w.]+)', src[:200]) enc = match.group(1).decode('utf-8') if match else 'utf-8' src = src.decode(enc) @@ -46,7 +46,7 @@ def compile_recipe(src): 'AutomaticNewsRecipe':AutomaticNewsRecipe, 'time':time, 're':re, 'BeautifulSoup':BeautifulSoup, - 'unicode': unicode_type, + 'unicode': str, 'unichr': codepoint_to_chr, 'xrange': range, } diff --git a/src/calibre/web/feeds/recipes/collection.py b/src/calibre/web/feeds/recipes/collection.py index c9716b7d3d..53f7efee3b 100644 --- a/src/calibre/web/feeds/recipes/collection.py +++ b/src/calibre/web/feeds/recipes/collection.py @@ -19,7 +19,7 @@ from calibre.utils.iso8601 import parse_iso8601 from calibre.utils.date import now as nowf, utcnow, local_tz, isoformat, EPOCH, UNDEFINED_DATE from calibre.utils.recycle_bin import delete_file -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems NS = 'http://calibre-ebook.com/recipe_collection' E = ElementMaker(namespace=NS, nsmap={None:NS}) @@ -54,7 +54,7 @@ def attr(n, d): if ns is True: ns = 'yes' return E.recipe({ - 'id' : unicode_type(urn), + 'id' : str(urn), 'title' : attr('title', _('Unknown')), 'author' : attr('__author__', default_author), 'language' : attr('language', 'und'), @@ -81,7 +81,7 @@ def serialize_collection(mapping_of_recipe_classes): traceback.print_exc() continue collection.append(recipe) - collection.set('count', unicode_type(len(collection))) + collection.set('count', str(len(collection))) return etree.tostring(collection, encoding='utf-8', xml_declaration=True, pretty_print=True) @@ -139,14 +139,14 @@ def update_custom_recipes(script_ids): bdir = os.path.dirname(custom_recipes.file_path) for id_, title, script in script_ids: - id_ = unicode_type(int(id_)) + id_ = str(int(id_)) existing = custom_recipes.get(id_, None) if existing is None: fname = custom_recipe_filename(id_, title) else: fname = existing[1] - if isinstance(script, unicode_type): + if isinstance(script, str): script = script.encode('utf-8') custom_recipes[id_] = (title, fname) @@ -172,10 +172,10 @@ def add_custom_recipes(script_map): bdir = os.path.dirname(custom_recipes.file_path) with custom_recipes: for title, script in iteritems(script_map): - fid = unicode_type(id_) + fid = str(id_) fname = custom_recipe_filename(fid, title) - if isinstance(script, unicode_type): + if isinstance(script, str): script = script.encode('utf-8') custom_recipes[fid] = (title, fname) @@ -190,7 +190,7 @@ def add_custom_recipes(script_map): def remove_custom_recipe(id_): from calibre.web.feeds.recipes import custom_recipes - id_ = unicode_type(int(id_)) + id_ = str(int(id_)) existing = custom_recipes.get(id_, None) if existing is not None: bdir = os.path.dirname(custom_recipes.file_path) @@ -204,7 +204,7 @@ def remove_custom_recipe(id_): def get_custom_recipe(id_): from calibre.web.feeds.recipes import custom_recipes - id_ = unicode_type(int(id_)) + id_ = str(int(id_)) existing = custom_recipes.get(id_, None) if existing is not None: bdir = os.path.dirname(custom_recipes.file_path) @@ -403,7 +403,7 @@ def serialize_schedule(self, typ, schedule): elif typ == 'day/time': text = '%d:%d:%d'%schedule elif typ in ('days_of_week', 'days_of_month'): - dw = ','.join(map(unicode_type, map(int, schedule[0]))) + dw = ','.join(map(str, map(int, schedule[0]))) text = '%s:%d:%d'%(dw, schedule[1], schedule[2]) else: raise ValueError('Unknown schedule type: %r'%typ) @@ -552,8 +552,8 @@ def migrate_old_conf(self, old_conf_path): username, password = c[k] except: username = password = '' - self.set_account_info(urn, unicode_type(username), - unicode_type(password)) + self.set_account_info(urn, str(username), + str(password)) except: continue del c diff --git a/src/calibre/web/feeds/recipes/model.py b/src/calibre/web/feeds/recipes/model.py index a5e7a801a5..b934471a49 100644 --- a/src/calibre/web/feeds/recipes/model.py +++ b/src/calibre/web/feeds/recipes/model.py @@ -20,7 +20,7 @@ get_custom_recipe_collection, remove_custom_recipe, update_custom_recipe, update_custom_recipes ) -from polyglot.builtins import iteritems, unicode_type +from polyglot.builtins import iteritems class NewsTreeItem: @@ -309,7 +309,7 @@ def get_matches(self, location, query): def search(self, query): results = [] try: - query = unicode_type(query).strip() + query = str(query).strip() if query: results = self.parse(query) if not results: diff --git a/src/calibre/web/feeds/templates.py b/src/calibre/web/feeds/templates.py index 6995216c22..961582bd15 100644 --- a/src/calibre/web/feeds/templates.py +++ b/src/calibre/web/feeds/templates.py @@ -13,13 +13,12 @@ TABLE, TD, TR from calibre import strftime, isbytestring -from polyglot.builtins import unicode_type def attrs(*args, **kw): rescale = kw.pop('rescale', None) if rescale is not None: - kw['data-calibre-rescale'] = unicode_type(rescale) + kw['data-calibre-rescale'] = str(rescale) if args: kw['class'] = ' '.join(args) return kw @@ -79,7 +78,7 @@ def _generate(self, article, style=None, extra_css=None): self.root = HTML(head, BODY(H2(article.title), DIV())) div = self.root.find('body').find('div') - if elements and isinstance(elements[0], unicode_type): + if elements and isinstance(elements[0], str): div.text = elements[0] elements = list(elements)[1:] for elem in elements: diff --git a/src/calibre/web/fetch/simple.py b/src/calibre/web/fetch/simple.py index 3a3168e190..54c7910e95 100644 --- a/src/calibre/web/fetch/simple.py +++ b/src/calibre/web/fetch/simple.py @@ -29,7 +29,6 @@ from calibre.utils.imghdr import what from calibre.utils.logging import Log from calibre.web.fetch.utils import rescale_image -from polyglot.builtins import unicode_type from polyglot.http_client import responses from polyglot.urllib import ( URLError, quote, url2pathname, urljoin, urlparse, urlsplit, urlunparse, @@ -108,7 +107,7 @@ def save_soup(soup, target): if path and os.path.isfile(path) and os.path.exists(path) and os.path.isabs(path): tag[key] = unicode_path(relpath(path, selfdir).replace(os.sep, '/')) - html = unicode_type(soup) + html = str(soup) with open(target, 'wb') as f: f.write(html.encode('utf-8')) @@ -138,7 +137,7 @@ class RecursiveFetcher: def __init__(self, options, log, image_map={}, css_map={}, job_info=None): bd = options.dir - if not isinstance(bd, unicode_type): + if not isinstance(bd, str): bd = bd.decode(filesystem_encoding) self.base_dir = os.path.abspath(os.path.expanduser(bd)) @@ -356,7 +355,7 @@ def process_stylesheets(self, soup, baseurl): except Exception: self.log.exception('Could not fetch stylesheet ', iurl) continue - stylepath = os.path.join(diskpath, 'style'+unicode_type(c)+'.css') + stylepath = os.path.join(diskpath, 'style'+str(c)+'.css') with self.stylemap_lock: self.stylemap[iurl] = stylepath with open(stylepath, 'wb') as x: @@ -364,7 +363,7 @@ def process_stylesheets(self, soup, baseurl): tag['href'] = stylepath else: for ns in tag.findAll(text=True): - src = unicode_type(ns) + src = str(ns) m = self.__class__.CSS_IMPORT_PATTERN.search(src) if m: iurl = m.group(1) @@ -383,7 +382,7 @@ def process_stylesheets(self, soup, baseurl): self.log.exception('Could not fetch stylesheet ', iurl) continue c += 1 - stylepath = os.path.join(diskpath, 'style'+unicode_type(c)+'.css') + stylepath = os.path.join(diskpath, 'style'+str(c)+'.css') with self.stylemap_lock: self.stylemap[iurl] = stylepath with open(stylepath, 'wb') as x: @@ -427,7 +426,7 @@ def process_images(self, soup, baseurl): self.log.exception('Could not fetch image ', iurl) continue c += 1 - fname = ascii_filename('img'+unicode_type(c)) + fname = ascii_filename('img'+str(c)) data = self.preprocess_image_ext(data, iurl) if self.preprocess_image_ext is not None else data if data is None: continue @@ -523,7 +522,7 @@ def process_links(self, soup, baseurl, recursion_level, into_dir='links'): continue if self.files > self.max_files: return res - linkdir = 'link'+unicode_type(c) if into_dir else '' + linkdir = 'link'+str(c) if into_dir else '' linkdiskpath = os.path.join(diskpath, linkdir) if not os.path.exists(linkdiskpath): os.mkdir(linkdiskpath) @@ -554,7 +553,7 @@ def process_links(self, soup, baseurl, recursion_level, into_dir='links'): self.process_stylesheets(soup, newbaseurl) _fname = basename(iurl) - if not isinstance(_fname, unicode_type): + if not isinstance(_fname, str): _fname.decode('latin1', 'replace') _fname = _fname.replace('%', '').replace(os.sep, '') _fname = ascii_filename(_fname)