From 5d111a3c04d1c1fb6d0f1e8cf5a7475b66252539 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Wed, 16 Dec 2015 17:48:26 -0800 Subject: [PATCH] Refactor tesseract --pdfrenderer calls to tesseract.py --- ocrmypdf/main.py | 28 ++++++++-------------------- ocrmypdf/tesseract.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/ocrmypdf/main.py b/ocrmypdf/main.py index 6ce98907..7483c8bb 100755 --- a/ocrmypdf/main.py +++ b/ocrmypdf/main.py @@ -654,26 +654,14 @@ def tesseract_ocr_and_render_pdf( re_symlink(input_pdf, output_file) return - args_tesseract = [ - 'tesseract', - '-l', '+'.join(options.language), - input_image, - os.path.splitext(output_file)[0], # Tesseract appends suffix - 'pdf' - ] + options.tesseract_config - p = Popen(args_tesseract, close_fds=True, stdout=PIPE, stderr=PIPE, - universal_newlines=True) - - try: - stdout, stderr = p.communicate(timeout=options.tesseract_timeout) - if stdout: - log.info(stdout) - if stderr: - log.error(stderr) - except TimeoutExpired: - p.kill() - log.info("Tesseract - page timed out") - re_symlink(input_pdf, output_file) + tesseract.generate_pdf( + input_image=input_image, + skip_pdf=input_pdf, + output_pdf=output_file, + language=options.language, + tessconfig=options.tesseract_config, + timeout=options.tesseract_timeout, + log=log) @transform( diff --git a/ocrmypdf/tesseract.py b/ocrmypdf/tesseract.py index 1505476a..38a29f98 100644 --- a/ocrmypdf/tesseract.py +++ b/ocrmypdf/tesseract.py @@ -134,3 +134,36 @@ def generate_hocr(input_file, output_hocr, language: list, tessconfig: list, f_out.write(line) +def generate_pdf(input_image, skip_pdf, output_pdf, language: list, + tessconfig: list, timeout: float, log): + '''Use Tesseract to render a PDF. + + input_image -- image to analyze + skip_pdf -- if we time out, use this file as output + language -- list of languages to consider + tessconfig -- tesseract configuration + timeout -- timeout (seconds) + log -- logger object + ''' + + args_tesseract = [ + 'tesseract', + '-l', '+'.join(language), + input_image, + os.path.splitext(output_pdf)[0], # Tesseract appends suffix + 'pdf' + ] + tessconfig + p = Popen(args_tesseract, close_fds=True, stdout=PIPE, stderr=PIPE, + universal_newlines=True) + + try: + stdout, stderr = p.communicate(timeout=timeout) + if stdout: + log.info(stdout) + if stderr: + log.error(stderr) + except TimeoutExpired: + p.kill() + log.info("Tesseract - page timed out") + shutil.copy(skip_pdf, output_pdf) +