#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import zipfile import filetype from PIL import Image from io import BytesIO from hashlib import md5 from slugify import slugify def epubwriter(dirout, cached, xhtmls, css): title, cover_img, chapters, _, imgs_files = cached.load() zf = zipfile.ZipFile(f'{dirout.joinpath(slugify(title))}.epub', 'w') zf.writestr('stylesheet.css', css) zf.writestr('mimetype', 'application/epub+zip') zf.writestr('META-INF/container.xml', metainfcontainer) cover_ext = filetype.guess(cover_img).extension cover_mime = filetype.guess(cover_img).mime zf.writestr('content.opf', contentopf(title, xhtmls, imgs_files, cover_ext, cover_mime)) zf.writestr('toc.ncx', tocncx(title, [c[0] for c in chapters])) im = Image.open(BytesIO(cover_img)) width, height = im.size zf.writestr('titlepage.xhtml', titlepagexhtml('cover.'+cover_ext, width, height)) for i, s in enumerate(xhtmls): zf.writestr(f'text/{i}.xhtml', s) zf.writestr('cover.'+cover_ext, cover_img) for i, b in imgs_files.items(): zf.writestr(f'images/{i}.{filetype.guess(b).extension}', b) zf.close() def contentopf(title, xhtmls, imgfs, cover_ext, cover_mime): return f''' {title} urn:uuid:book{md5(title.encode()).hexdigest()} '''+ ''.join([f''' ''' for i in range(len(xhtmls))]) + ''.join([f''' ''' for i, b in imgfs.items()]) +''' '''+ ''.join([f''' ''' for i in range(len(xhtmls))]) +''' ''' def tocncx(title, chapters): return f''' {title} Cover ''' + ''.join([f''' {c} ''' for i, c in enumerate(chapters)]) + ''' ''' def titlepagexhtml(filename, width, height): return ''' Cover
'''+f'''
''' metainfcontainer = ''' '''