# -*- coding: utf-8 -*- import os import xml.etree.ElementTree as ET import zipfile import re from urllib.parse import unquote import lxml.html from io import BytesIO from PIL import Image from ox import strip_tags, decode_html, normalize_name from utils import find_isbns, get_language, to_isbn13 import logging logging.getLogger('PIL').setLevel(logging.ERROR) logger = logging.getLogger(__name__) def get_ratio(data): try: img = Image.open(BytesIO(data)) return img.size[0]/img.size[1] except: return -1 def normpath(path): return '/'.join(os.path.normpath(path).split(os.sep)) def cover(path): logger.debug('cover %s', path) data = None try: z = zipfile.ZipFile(path) except zipfile.BadZipFile: logger.debug('invalid epub file %s', path) return data def use(filename): logger.debug('using %s', filename) try: data = z.read(filename) except: return None r = get_ratio(data) if r < 0.3 or r > 2: return None return data files = [] for f in z.filelist: if f.filename == 'calibre-logo.png': continue if 'cover' in f.filename.lower() and f.filename.split('.')[-1] in ('jpg', 'jpeg', 'png'): return use(f.filename) files.append(f.filename) opf = [f for f in files if f.endswith('opf')] if opf: #logger.debug('opf: %s', z.read(opf[0]).decode()) info = ET.fromstring(z.read(opf[0])) metadata = info.findall('{http://www.idpf.org/2007/opf}metadata') if metadata: metadata = metadata[0] manifest = info.findall('{http://www.idpf.org/2007/opf}manifest') if manifest: manifest = manifest[0] if metadata and manifest: for e in list(metadata): if e.tag == '{http://www.idpf.org/2007/opf}meta' and e.attrib.get('name') == 'cover': cover_id = e.attrib['content'] for e in list(manifest): if e.attrib['id'] == cover_id: filename = unquote(e.attrib['href']) filename = normpath(os.path.join(os.path.dirname(opf[0]), filename)) if filename in files: return use(filename) if manifest: images = [e for e in list(manifest) if 'image' in e.attrib['media-type']] if images: image_data = [] for e in images: filename = unquote(e.attrib['href']) filename = normpath(os.path.join(os.path.dirname(opf[0]), filename)) if filename in files: image_data.append(filename) if image_data: image_data.sort(key=lambda name: z.getinfo(name).file_size) return use(image_data[-1]) for e in list(manifest): if 'html' in e.attrib['media-type']: filename = unquote(e.attrib['href']) filename = normpath(os.path.join(os.path.dirname(opf[0]), filename)) html = z.read(filename).decode('utf-8', 'ignore') img = re.compile('