1
0
mirror of https://github.com/gryf/ebook-converter.git synced 2026-03-22 18:33:34 +01:00

Cleaned up __init__.py for main module

This commit is contained in:
2021-01-05 19:48:45 +01:00
parent 8a757f60a6
commit b2f161670a
15 changed files with 55 additions and 85 deletions

View File

@@ -1,26 +0,0 @@
import os
import re
from functools import partial
from ebook_converter import constants_old
from ebook_converter.utils import entities
class CurrentDir(object):
def __init__(self, path):
self.path = path
self.cwd = None
def __enter__(self, *args):
self.cwd = os.getcwd()
os.chdir(self.path)
return self.cwd
def __exit__(self, *args):
try:
os.chdir(self.cwd)
except EnvironmentError:
# The previous CWD no longer exists
pass

View File

@@ -3,8 +3,8 @@ Defines the plugin system for conversions.
""" """
import re, os, shutil, numbers import re, os, shutil, numbers
from ebook_converter import CurrentDir
from ebook_converter.customize import Plugin from ebook_converter.customize import Plugin
from ebook_converter.utils import directory
class ConversionOption(object): class ConversionOption(object):
@@ -204,7 +204,7 @@ class InputFormatPlugin(Plugin):
# In case stdout is broken # In case stdout is broken
pass pass
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
for x in os.listdir('.'): for x in os.listdir('.'):
shutil.rmtree(x) if os.path.isdir(x) else os.remove(x) shutil.rmtree(x) if os.path.isdir(x) else os.remove(x)

View File

@@ -5,8 +5,8 @@ import shutil, textwrap, codecs, os
from ebook_converter import constants as const from ebook_converter import constants as const
from ebook_converter.customize.conversion import InputFormatPlugin, OptionRecommendation from ebook_converter.customize.conversion import InputFormatPlugin, OptionRecommendation
from ebook_converter import CurrentDir
from ebook_converter.ptempfile import PersistentTemporaryDirectory from ebook_converter.ptempfile import PersistentTemporaryDirectory
from ebook_converter.utils import directory
__license__ = 'GPL v3' __license__ = 'GPL v3'
@@ -98,7 +98,7 @@ class ComicInput(InputFormatPlugin):
tdir = PersistentTemporaryDirectory('_comic_collection') tdir = PersistentTemporaryDirectory('_comic_collection')
zipextract(stream, tdir) zipextract(stream, tdir)
comics = [] comics = []
with CurrentDir(tdir): with directory.CurrentDir(tdir):
if not os.path.exists('comics.txt'): if not os.path.exists('comics.txt'):
raise ValueError(( raise ValueError((
'%s is not a valid comic collection' '%s is not a valid comic collection'

View File

@@ -8,16 +8,11 @@ from ebook_converter.ebooks.oeb import base
from ebook_converter.ebooks.oeb import parse_utils from ebook_converter.ebooks.oeb import parse_utils
from ebook_converter.customize.conversion import OutputFormatPlugin from ebook_converter.customize.conversion import OutputFormatPlugin
from ebook_converter.customize.conversion import OptionRecommendation from ebook_converter.customize.conversion import OptionRecommendation
from ebook_converter.ptempfile import TemporaryDirectory from ebook_converter.ptempfile import TemporaryDirectory
from ebook_converter import CurrentDir
from ebook_converter.polyglot.builtins import as_bytes from ebook_converter.polyglot.builtins import as_bytes
from ebook_converter.utils import directory
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
block_level_tags = ( block_level_tags = (
'address', 'address',
'body', 'body',
@@ -320,7 +315,7 @@ class EPUBOutput(OutputFormatPlugin):
raise ValueError('UUID identifier %r is invalid'% _uuid) raise ValueError('UUID identifier %r is invalid'% _uuid)
key = bytearray(from_hex_bytes((key + key)[:32])) key = bytearray(from_hex_bytes((key + key)[:32]))
paths = [] paths = []
with CurrentDir(tdir): with directory.CurrentDir(tdir):
paths = [os.path.join(*x.split('/')) for x in uris] paths = [os.path.join(*x.split('/')) for x in uris]
uris = dict(zip(uris, paths)) uris = dict(zip(uris, paths))
fonts = [] fonts = []

View File

@@ -5,16 +5,12 @@ import shutil
from lxml import etree from lxml import etree
from ebook_converter import CurrentDir
from ebook_converter.customize.conversion import OutputFormatPlugin, OptionRecommendation from ebook_converter.customize.conversion import OutputFormatPlugin, OptionRecommendation
from ebook_converter.ebooks.oeb.base import element from ebook_converter.ebooks.oeb.base import element
from ebook_converter.polyglot.urllib import unquote from ebook_converter.polyglot.urllib import unquote
from ebook_converter.ptempfile import PersistentTemporaryDirectory from ebook_converter.ptempfile import PersistentTemporaryDirectory
from ebook_converter.utils.cleantext import clean_xml_chars from ebook_converter.utils.cleantext import clean_xml_chars
from ebook_converter.utils import directory
__license__ = 'GPL 3'
__copyright__ = '2010, Fabian Grassl <fg@jusmeum.de>'
__docformat__ = 'restructuredtext en'
def relpath(*args): def relpath(*args):
@@ -52,7 +48,7 @@ class HTMLOutput(OutputFormatPlugin):
Generate table of contents Generate table of contents
''' '''
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
def build_node(current_node, parent=None): def build_node(current_node, parent=None):
if parent is None: if parent is None:
parent = etree.Element('ul') parent = etree.Element('ul')
@@ -158,7 +154,7 @@ class HTMLOutput(OutputFormatPlugin):
t = t.encode('utf-8') t = t.encode('utf-8')
f.write(t) f.write(t)
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
for item in oeb_book.manifest: for item in oeb_book.manifest:
path = os.path.abspath(unquote(item.href)) path = os.path.abspath(unquote(item.href))
dir = os.path.dirname(path) dir = os.path.dirname(path)

View File

@@ -5,15 +5,10 @@ from lxml import etree
from ebook_converter.customize.conversion import (OutputFormatPlugin, from ebook_converter.customize.conversion import (OutputFormatPlugin,
OptionRecommendation) OptionRecommendation)
from ebook_converter import CurrentDir
from ebook_converter.polyglot.urllib import unquote from ebook_converter.polyglot.urllib import unquote
from ebook_converter.ebooks.oeb.base import OPF_MIME, NCX_MIME, PAGE_MAP_MIME, OEB_STYLES from ebook_converter.ebooks.oeb.base import OPF_MIME, NCX_MIME, PAGE_MAP_MIME, OEB_STYLES
from ebook_converter.ebooks.oeb.normalize_css import condense_sheet from ebook_converter.ebooks.oeb.normalize_css import condense_sheet
from ebook_converter.utils import directory
__license__ = 'GPL 3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
class OEBOutput(OutputFormatPlugin): class OEBOutput(OutputFormatPlugin):
@@ -30,7 +25,7 @@ class OEBOutput(OutputFormatPlugin):
self.log, self.opts = log, opts self.log, self.opts = log, opts
if not os.path.exists(output_path): if not os.path.exists(output_path):
os.makedirs(output_path) os.makedirs(output_path)
with CurrentDir(output_path): with directory.CurrentDir(output_path):
results = oeb_book.to_opf2(page_map=True) results = oeb_book.to_opf2(page_map=True)
for key in (OPF_MIME, NCX_MIME, PAGE_MAP_MIME): for key in (OPF_MIME, NCX_MIME, PAGE_MAP_MIME):
href, root = results.pop(key, [None, None]) href, root = results.pop(key, [None, None])

View File

@@ -1,7 +1,6 @@
import glob import glob
import os import os
from ebook_converter import CurrentDir
from ebook_converter.ebooks.mobi import MobiError from ebook_converter.ebooks.mobi import MobiError
from ebook_converter.ebooks.mobi.reader.mobi6 import MobiReader from ebook_converter.ebooks.mobi.reader.mobi6 import MobiReader
from ebook_converter.ebooks.mobi.reader.headers import MetadataHeader from ebook_converter.ebooks.mobi.reader.headers import MetadataHeader
@@ -11,6 +10,7 @@ from ebook_converter.ebooks.mobi.reader.mobi8 import Mobi8Reader
from ebook_converter.ebooks.conversion.plumber import Plumber, create_oebbook from ebook_converter.ebooks.conversion.plumber import Plumber, create_oebbook
from ebook_converter.customize.ui import plugin_for_input_format from ebook_converter.customize.ui import plugin_for_input_format
from ebook_converter.customize.ui import plugin_for_output_format from ebook_converter.customize.ui import plugin_for_output_format
from ebook_converter.utils import directory
from ebook_converter.utils.ipc.simple_worker import fork_job from ebook_converter.utils.ipc.simple_worker import fork_job
@@ -27,7 +27,7 @@ def do_explode(path, dest):
with open(path, 'rb') as stream: with open(path, 'rb') as stream:
mr = MobiReader(stream, default_log, None, None) mr = MobiReader(stream, default_log, None, None)
with CurrentDir(dest): with directory.CurrentDir(dest):
mr = Mobi8Reader(mr, default_log) mr = Mobi8Reader(mr, default_log)
opf = os.path.abspath(mr()) opf = os.path.abspath(mr())
try: try:

View File

@@ -13,7 +13,7 @@ from odf.opendocument import load as odLoad
from odf.draw import Frame as odFrame, Image as odImage from odf.draw import Frame as odFrame, Image as odImage
from odf.namespaces import TEXTNS as odTEXTNS from odf.namespaces import TEXTNS as odTEXTNS
from ebook_converter import CurrentDir from ebook_converter.utils import directory
from ebook_converter.ebooks.oeb.base import _css_logger from ebook_converter.ebooks.oeb.base import _css_logger
from ebook_converter.polyglot.builtins import as_bytes from ebook_converter.polyglot.builtins import as_bytes
@@ -266,7 +266,7 @@ class Extract(ODF2XHTML):
if not os.path.exists(odir): if not os.path.exists(odir):
os.makedirs(odir) os.makedirs(odir)
with CurrentDir(odir): with directory.CurrentDir(odir):
log('Extracting ODT file...') log('Extracting ODT file...')
stream.seek(0) stream.seek(0)
mi = get_metadata(stream, 'odt') mi = get_metadata(stream, 'odt')

View File

@@ -16,7 +16,6 @@ import css_parser
from lxml import etree from lxml import etree
from ebook_converter import constants as const from ebook_converter import constants as const
from ebook_converter import CurrentDir
from ebook_converter.customize.ui import plugin_for_input_format, plugin_for_output_format from ebook_converter.customize.ui import plugin_for_input_format, plugin_for_output_format
from ebook_converter.ebooks import escape_xpath_attr from ebook_converter.ebooks import escape_xpath_attr
from ebook_converter.ebooks.chardet import xml_to_unicode from ebook_converter.ebooks.chardet import xml_to_unicode
@@ -41,6 +40,7 @@ from ebook_converter.ebooks.oeb.polish.utils import (
CommentFinder, PositionFinder, guess_type, parse_css CommentFinder, PositionFinder, guess_type, parse_css
) )
from ebook_converter.ptempfile import PersistentTemporaryDirectory, PersistentTemporaryFile from ebook_converter.ptempfile import PersistentTemporaryDirectory, PersistentTemporaryFile
from ebook_converter.utils import directory
from ebook_converter.utils.filenames import hardlink_file, nlinks_file from ebook_converter.utils.filenames import hardlink_file, nlinks_file
from ebook_converter.utils.ipc.simple_worker import WorkerError, fork_job from ebook_converter.utils.ipc.simple_worker import WorkerError, fork_job
from ebook_converter.utils.logging import default_log from ebook_converter.utils.logging import default_log
@@ -1393,7 +1393,7 @@ def do_explode(path, dest):
with open(path, 'rb') as stream: with open(path, 'rb') as stream:
mr = MobiReader(stream, default_log, None, None) mr = MobiReader(stream, default_log, None, None)
with CurrentDir(dest): with directory.CurrentDir(dest):
mr = Mobi8Reader(mr, default_log, for_tweak=True) mr = Mobi8Reader(mr, default_log, for_tweak=True)
opf = os.path.abspath(mr()) opf = os.path.abspath(mr())
obfuscated_fonts = mr.encrypted_fonts obfuscated_fonts = mr.encrypted_fonts

View File

@@ -6,16 +6,11 @@ import re
import struct import struct
import zlib import zlib
from ebook_converter import CurrentDir
from ebook_converter.ebooks import DRMError from ebook_converter.ebooks import DRMError
from ebook_converter.ebooks.metadata.opf2 import OPFCreator from ebook_converter.ebooks.metadata.opf2 import OPFCreator
from ebook_converter.ebooks.pdb.ereader import EreaderError from ebook_converter.ebooks.pdb.ereader import EreaderError
from ebook_converter.ebooks.pdb.formatreader import FormatReader from ebook_converter.ebooks.pdb.formatreader import FormatReader
from ebook_converter.utils import directory
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
class HeaderRecord(object): class HeaderRecord(object):
@@ -149,7 +144,7 @@ class Reader132(FormatReader):
html += '</body></html>' html += '</body></html>'
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
with open('index.html', 'wb') as index: with open('index.html', 'wb') as index:
self.log.debug('Writing text to index.html') self.log.debug('Writing text to index.html')
index.write(html.encode('utf-8')) index.write(html.encode('utf-8'))
@@ -157,7 +152,7 @@ class Reader132(FormatReader):
if not os.path.exists(os.path.join(output_dir, 'images/')): if not os.path.exists(os.path.join(output_dir, 'images/')):
os.makedirs(os.path.join(output_dir, 'images/')) os.makedirs(os.path.join(output_dir, 'images/'))
images = [] images = []
with CurrentDir(os.path.join(output_dir, 'images/')): with directory.CurrentDir(os.path.join(output_dir, 'images/')):
for i in range(0, self.header_record.num_image_pages): for i in range(0, self.header_record.num_image_pages):
name, img = self.get_image(self.header_record.image_data_offset + i) name, img = self.get_image(self.header_record.image_data_offset + i)
images.append(name) images.append(name)
@@ -170,7 +165,7 @@ class Reader132(FormatReader):
return opf_path return opf_path
def create_opf(self, output_dir, images, toc): def create_opf(self, output_dir, images, toc):
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
if 'cover.png' in images: if 'cover.png' in images:
self.mi.cover = os.path.join('images', 'cover.png') self.mi.cover = os.path.join('images', 'cover.png')
@@ -210,7 +205,7 @@ class Reader132(FormatReader):
if not os.path.exists(output_dir): if not os.path.exists(output_dir):
os.makedirs(output_dir) os.makedirs(output_dir)
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
for i in range(0, self.header_record.num_image_pages): for i in range(0, self.header_record.num_image_pages):
name, img = self.get_image(self.header_record.image_data_offset + i) name, img = self.get_image(self.header_record.image_data_offset + i)
with open(name, 'wb') as imgf: with open(name, 'wb') as imgf:

View File

@@ -5,17 +5,12 @@ Makebook.
import os import os
import struct import struct
from ebook_converter import CurrentDir from ebook_converter.utils import directory
from ebook_converter.ebooks.metadata.opf2 import OPFCreator from ebook_converter.ebooks.metadata.opf2 import OPFCreator
from ebook_converter.ebooks.pdb.formatreader import FormatReader from ebook_converter.ebooks.pdb.formatreader import FormatReader
from ebook_converter.ebooks.pdb.ereader import EreaderError from ebook_converter.ebooks.pdb.ereader import EreaderError
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
class HeaderRecord(object): class HeaderRecord(object):
''' '''
The first record in the file is always the header record. It holds The first record in the file is always the header record. It holds
@@ -102,7 +97,7 @@ class Reader202(FormatReader):
html = '<html><head><title>%s</title></head><body>%s</body></html>' % \ html = '<html><head><title>%s</title></head><body>%s</body></html>' % \
(title, pml_to_html(pml)) (title, pml_to_html(pml))
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
with open('index.html', 'wb') as index: with open('index.html', 'wb') as index:
self.log.debug('Writing text to index.html') self.log.debug('Writing text to index.html')
index.write(html.encode('utf-8')) index.write(html.encode('utf-8'))
@@ -110,7 +105,7 @@ class Reader202(FormatReader):
if not os.path.exists(os.path.join(output_dir, 'images/')): if not os.path.exists(os.path.join(output_dir, 'images/')):
os.makedirs(os.path.join(output_dir, 'images/')) os.makedirs(os.path.join(output_dir, 'images/'))
images = [] images = []
with CurrentDir(os.path.join(output_dir, 'images/')): with directory.CurrentDir(os.path.join(output_dir, 'images/')):
for i in range(self.header_record.non_text_offset, len(self.sections)): for i in range(self.header_record.non_text_offset, len(self.sections)):
name, img = self.get_image(i) name, img = self.get_image(i)
if name: if name:
@@ -124,7 +119,7 @@ class Reader202(FormatReader):
return opf_path return opf_path
def create_opf(self, output_dir, images): def create_opf(self, output_dir, images):
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
opf = OPFCreator(output_dir, self.mi) opf = OPFCreator(output_dir, self.mi)
manifest = [('index.html', None)] manifest = [('index.html', None)]
@@ -159,7 +154,7 @@ class Reader202(FormatReader):
if not os.path.exists(output_dir): if not os.path.exists(output_dir):
os.makedirs(output_dir) os.makedirs(output_dir)
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
for i in range(0, self.header_record.num_image_pages): for i in range(0, self.header_record.num_image_pages):
name, img = self.get_image(self.header_record.image_data_offset + i) name, img = self.get_image(self.header_record.image_data_offset + i)
with open(name, 'wb') as imgf: with open(name, 'wb') as imgf:

View File

@@ -4,7 +4,7 @@ import zlib
from collections import OrderedDict from collections import OrderedDict
from ebook_converter import CurrentDir from ebook_converter.utils import directory
from ebook_converter.ebooks.pdb.formatreader import FormatReader from ebook_converter.ebooks.pdb.formatreader import FormatReader
from ebook_converter.ebooks.compression.palmdoc import decompress_doc from ebook_converter.ebooks.compression.palmdoc import decompress_doc
from ebook_converter.utils.imghdr import identify from ebook_converter.utils.imghdr import identify
@@ -358,7 +358,7 @@ class Reader(FormatReader):
# text recored into a separate file. We will reference the # text recored into a separate file. We will reference the
# home.html file as the first file and let the HTML input # home.html file as the first file and let the HTML input
# plugin assemble the order based on hyperlinks. # plugin assemble the order based on hyperlinks.
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
for uid, num in self.uid_text_secion_number.items(): for uid, num in self.uid_text_secion_number.items():
self.log.debug('Writing record with uid: %s as %s.html' % (uid, uid)) self.log.debug('Writing record with uid: %s as %s.html' % (uid, uid))
with open('%s.html' % uid, 'wb') as htmlf: with open('%s.html' % uid, 'wb') as htmlf:
@@ -377,7 +377,7 @@ class Reader(FormatReader):
images = set() images = set()
if not os.path.exists(os.path.join(output_dir, 'images/')): if not os.path.exists(os.path.join(output_dir, 'images/')):
os.makedirs(os.path.join(output_dir, 'images/')) os.makedirs(os.path.join(output_dir, 'images/'))
with CurrentDir(os.path.join(output_dir, 'images/')): with directory.CurrentDir(os.path.join(output_dir, 'images/')):
# Single images. # Single images.
for uid, num in self.uid_image_section_number.items(): for uid, num in self.uid_image_section_number.items():
section_header, section_data = self.sections[num] section_header, section_data = self.sections[num]

View File

@@ -6,11 +6,11 @@ import subprocess
from lxml import etree from lxml import etree
from ebook_converter import CurrentDir
from ebook_converter.ebooks import ConversionError, DRMError from ebook_converter.ebooks import ConversionError, DRMError
from ebook_converter.ebooks.chardet import xml_to_unicode from ebook_converter.ebooks.chardet import xml_to_unicode
from ebook_converter.ptempfile import PersistentTemporaryFile from ebook_converter.ptempfile import PersistentTemporaryFile
from ebook_converter.utils.cleantext import clean_xml_chars from ebook_converter.utils.cleantext import clean_xml_chars
from ebook_converter.utils import directory
from ebook_converter.utils import entities from ebook_converter.utils import entities
from ebook_converter.utils.ipc import eintr_retry_call from ebook_converter.utils.ipc import eintr_retry_call
@@ -32,7 +32,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False):
with open(pdf_path, 'rb') as src, open(pdfsrc, 'wb') as dest: with open(pdf_path, 'rb') as src, open(pdfsrc, 'wb') as dest:
shutil.copyfileobj(src, dest) shutil.copyfileobj(src, dest)
with CurrentDir(output_dir): with directory.CurrentDir(output_dir):
def a(x): def a(x):
return os.path.basename(x) return os.path.basename(x)

View File

@@ -0,0 +1,20 @@
import os
class CurrentDir(object):
def __init__(self, path):
self.path = path
self.cwd = None
def __enter__(self, *args):
self.cwd = os.getcwd()
os.chdir(self.path)
return self.cwd
def __exit__(self, *args):
try:
os.chdir(self.cwd)
except EnvironmentError:
# The previous CWD no longer exists
pass

View File

@@ -15,8 +15,9 @@ from threading import Thread
from ebook_converter.constants_old import plugins from ebook_converter.constants_old import plugins
from ebook_converter.ptempfile import TemporaryDirectory from ebook_converter.ptempfile import TemporaryDirectory
from ebook_converter.utils.config_base import tweaks from ebook_converter.utils.config_base import tweaks
from ebook_converter.utils.filenames import atomic_rename from ebook_converter.utils import directory
from ebook_converter.utils import encoding as uenc from ebook_converter.utils import encoding as uenc
from ebook_converter.utils.filenames import atomic_rename
from ebook_converter.utils.imghdr import what from ebook_converter.utils.imghdr import what
# Utilities {{{ # Utilities {{{
@@ -646,11 +647,10 @@ def encode_jpeg(file_path, quality=80):
def test(): # {{{ def test(): # {{{
# TODO(gryf): move this test to separate file. # TODO(gryf): move this test to separate file.
from ebook_converter.ptempfile import TemporaryDirectory from ebook_converter.ptempfile import TemporaryDirectory
from ebook_converter import CurrentDir
from glob import glob from glob import glob
# TODO(gryf): make the sample image out of pillow or smth # TODO(gryf): make the sample image out of pillow or smth
# img = image_from_data(I('lt.png', data=True, allow_user_override=False)) # img = image_from_data(I('lt.png', data=True, allow_user_override=False))
with TemporaryDirectory() as tdir, CurrentDir(tdir): with TemporaryDirectory() as tdir, directory.CurrentDir(tdir):
save_image(img, 'test.jpg') save_image(img, 'test.jpg')
ret = optimize_jpeg('test.jpg') ret = optimize_jpeg('test.jpg')
if ret is not None: if ret is not None: