Skip to content

Commit

Permalink
Update calibre.py
Browse files Browse the repository at this point in the history
  • Loading branch information
zGadli committed Nov 12, 2023
1 parent 596dd91 commit 9392182
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions lncrawl/binders/calibre.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,49 @@
import logging
import os
import subprocess

logger = logging.getLogger(__name__)

EBOOK_CONVERT = "ebook-convert"
CALIBRE_LINK = "https://calibre-ebook.com/download"


def run_ebook_convert(*args):
def run_ebook_convert(*args) -> bool:
"""
Calls `ebook-convert` with given args
Visit https://manual.calibre-ebook.com/generated/en/ebook-convert.html for argument list.
"""
try:
isdebug = os.getenv("debug_mode")
with open(os.devnull, "w", encoding="utf8") as dumper:
subprocess.call(
subprocess.run(
args=[EBOOK_CONVERT] + list(args),
stdout=None if isdebug else dumper,
stderr=None if isdebug else dumper,
check=True
)

return True
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception("Failed to convert ebook with args: %s", list(args))

except subprocess.CalledProcessError:
logger.exception("Failed to convert ebook with args: %s", list(args))
return False
except Exception as e:
logger.exception("An unexpected error occurred: %s", str(e))
return False


def epub_to_calibre(app, epub_file, out_fmt):
def epub_to_calibre(app, epub_file, out_fmt) -> Union[str, None]:
if not os.path.exists(epub_file):
return None

epub_path = os.path.dirname(epub_file)
epub_file_name = os.path.basename(epub_file)
file_name_without_ext = epub_file_name.replace(".epub", "")
file_name_without_ext, _ = os.path.splitext(epub_file_name)

work_path = os.path.dirname(epub_path)
out_path = os.path.join(work_path, out_fmt)
out_file_name = file_name_without_ext + "." + out_fmt
out_file = os.path.join(out_path, out_file_name)

os.makedirs(out_path, exist_ok=True)

logger.debug('Converting "%s" to "%s"', epub_file, out_file)

args = [
epub_file,
out_file,
Expand Down Expand Up @@ -82,9 +79,7 @@ def epub_to_calibre(app, epub_file, out_fmt):
"--pdf-header-template",
'<p style="text-align:center; color:#555; font-size:0.9em">⦗ _TITLE_ &mdash; _SECTION_ ⦘</p>',
]

run_ebook_convert(*args)

if os.path.exists(out_file):
logger.info("Created: %s" % out_file_name)
return out_file
Expand All @@ -93,17 +88,15 @@ def epub_to_calibre(app, epub_file, out_fmt):
return None


def make_calibres(app, epubs, out_fmt):
def make_calibres(app, epubs, out_fmt) -> List[str]:
if out_fmt == "epub" or not epubs:
return epubs

if not run_ebook_convert("--version"):
logger.error("Install Calibre to generate %s: %s", out_fmt, CALIBRE_LINK),
return

out_files = []
for epub in epubs:
out = epub_to_calibre(app, epub, out_fmt)
out_files += [out]

return out_files
return out_files

0 comments on commit 9392182

Please sign in to comment.