Add pure python impl for detect file type

This commit is contained in:
2024-03-08 17:36:07 +08:00
parent 9cfb73759b
commit 3982a2b9c2
2 changed files with 18 additions and 4 deletions

21
epub.py
View File

@@ -11,12 +11,18 @@ from html.parser import HTMLParser
try: try:
import magic import magic
have_magic = True have_magic = True
have_filetype = False
except ImportError: except ImportError:
have_magic = False have_magic = False
print('Warning: python-magic not found. The mimetype in EPUB file may wrong.') # noqa: E501 try:
import platform import filetype
if platform.system() == "Windows": have_filetype = True
print('python-magic-bin is also needed on Windows.') except ImportError:
have_filetype = False
print('Warning: python-magic or filetype not found. The mimetype in EPUB file may wrong.') # noqa: E501
import platform
if platform.system() == "Windows":
print('python-magic-bin is also needed on Windows if you use magic.') # noqa: E501
# Add fallback property to ebooklib # Add fallback property to ebooklib
@@ -155,6 +161,10 @@ class HTMLImage:
with open(self.path, 'rb') as f: with open(self.path, 'rb') as f:
mime = magic.from_buffer(f.read(4096), True) mime = magic.from_buffer(f.read(4096), True)
self.epub_path = os.path.splitext(self.epub_path)[0] + get_extension(mime) # noqa: E501 self.epub_path = os.path.splitext(self.epub_path)[0] + get_extension(mime) # noqa: E501
if have_filetype:
with open(self.path, 'rb') as f:
mime = filetype.guess_mime(f.read(4096))
self.epub_path = os.path.splitext(self.epub_path)[0] + get_extension(mime) # noqa: E501
d = {'src': self.epub_path} d = {'src': self.epub_path}
if self.alt: if self.alt:
d['alt'] = self.alt d['alt'] = self.alt
@@ -281,6 +291,9 @@ class EpubFile:
if have_magic: if have_magic:
mime_type = magic.from_buffer(cover, mime=True) mime_type = magic.from_buffer(cover, mime=True)
file_name = 'cover' + get_extension(mime_type) file_name = 'cover' + get_extension(mime_type)
elif have_filetype:
mime_type = filetype.guess_mime(cover)
file_name = 'cover' + get_extension(mime_type)
else: else:
file_name = 'cover.png' file_name = 'cover.png'
self.epub.set_cover(file_name, cover) self.epub.set_cover(file_name, cover)

View File

@@ -5,3 +5,4 @@ lxml
python-magic python-magic
python-magic-bin ; sys_platform == 'win32' python-magic-bin ; sys_platform == 'win32'
requests requests
filetype