Using the OCRmyPDF API

OCRmyPDF originated as a command line program and continues to have this legacy, but parts of it can be imported and used in other Python applications.

Some applications may want to consider running ocrmypdf from a subprocess call anyway, as this provides isolation of its activities.

Example

OCRmyPDF provides one high-level function to run its main engine from an application. The parameters are symmetric to the command line arguments and largely have the same functions.

import ocrmypdf

if __name__ == '__main__':  # To ensure correct behavior on Windows and macOS
    ocrmypdf.ocr('input.pdf', 'output.pdf', deskew=True)

With some exceptions, all of the command line arguments are available and may be passed as equivalent keywords.

A few differences are that verbose and quiet are not available. Instead, output should be managed by configuring logging.

Parent process requirements

The ocrmypdf.ocr() function runs OCRmyPDF similar to command line execution. To do this, it will:

  • create a monitoring thread

  • create worker processes (on Linux, forking itself; on Windows and macOS, by spawning)

  • manage the signal flags of its worker processes

  • execute other subprocesses (forking and executing other programs)

The Python process that calls ocrmypdf.ocr() must be sufficiently privileged to perform these actions.

There currently is no option to manage how jobs are scheduled other than the argument jobs= which will limit the number of worker processes.

Creating a child process to call ocrmypdf.ocr() is suggested. That way your application will survive and remain interactive even if OCRmyPDF fails for any reason.

Programs that call ocrmypdf.ocr() should also install a SIGBUS signal handler (except on Windows), to raise an exception if access to a memory mapped file fails. OCRmyPDF may use memory mapping.

ocrmypdf.ocr() will take a threading lock to prevent multiple runs of itself in the same Python interpreter process. This is not thread-safe, because of how OCRmyPDF’s plugins and Python’s library import system work. If you need to parallelize OCRmyPDF, use processes.

Warning

On Windows and macOS, the script that calls ocrmypdf.ocr() must be protected by an “ifmain” guard (if __name__ == '__main__'). If you do not take at least one of these steps, process semantics will prevent OCRmyPDF from working correctly.

Warning

On macOS with Python 3.7, you must call multiprocessing.set_start_method("spawn")(). Without this, multiprocessing will be unstable. From the command line, OCRmyPDF does this automatically, but as an API user you must do this. See Python bpo-33725 for details. Python 3.8+ also resolve this automatically.

Logging

OCRmyPDF will log under loggers named ocrmypdf. In addition, it imports pdfminer and PIL, both of which post log messages under those logging namespaces.

You can configure the logging as desired for your application or call ocrmypdf.configure_logging() to configure logging the same way OCRmyPDF itself does. The command line parameters such as --quiet and --verbose have no equivalents in the API; you must use the provided configuration function or do configuration in a way that suits your use case.

Progress monitoring

OCRmyPDF uses the tqdm package to implement its progress bars. ocrmypdf.configure_logging() will set up logging output to sys.stderr in a way that is compatible with the display of the progress bar. Use ocrmypdf.ocr(...progress_bar=False) to disable the progress bar.

Exceptions

OCRmyPDF may throw standard Python exceptions, ocrmypdf.exceptions.* exceptions, some exceptions related to multiprocessing, and KeyboardInterrupt. The parent process should provide an exception handler. OCRmyPDF will clean up its temporary files and worker processes automatically when an exception occurs.

Programs that call OCRmyPDF should consider trapping KeyboardInterrupt so that they allow OCR to terminate with the whole program terminating.

When OCRmyPDF succeeds conditionally, it returns an integer exit code.

Reference

ocrmypdf.ocr(input_file: Union[BinaryIO, Path, AnyStr], output_file: Union[BinaryIO, Path, AnyStr], *, language: Optional[Iterable[str]] = None, image_dpi: Optional[int] = None, output_type=None, sidecar: Optional[Union[Path, AnyStr]] = None, jobs: Optional[int] = None, use_threads: Optional[bool] = None, title: Optional[str] = None, author: Optional[str] = None, subject: Optional[str] = None, keywords: Optional[str] = None, rotate_pages: Optional[bool] = None, remove_background: Optional[bool] = None, deskew: Optional[bool] = None, clean: Optional[bool] = None, clean_final: Optional[bool] = None, unpaper_args: Optional[str] = None, oversample: Optional[int] = None, remove_vectors: Optional[bool] = None, force_ocr: Optional[bool] = None, skip_text: Optional[bool] = None, redo_ocr: Optional[bool] = None, skip_big: Optional[float] = None, optimize: Optional[int] = None, jpg_quality: Optional[int] = None, png_quality: Optional[int] = None, jbig2_lossy: Optional[bool] = None, jbig2_page_group_size: Optional[int] = None, pages: Optional[str] = None, max_image_mpixels: Optional[float] = None, tesseract_config: Optional[Iterable[str]] = None, tesseract_pagesegmode: Optional[int] = None, tesseract_oem: Optional[int] = None, tesseract_thresholding: Optional[int] = None, pdf_renderer=None, tesseract_timeout: Optional[float] = None, rotate_pages_threshold: Optional[float] = None, pdfa_image_compression=None, user_words: Optional[PathLike] = None, user_patterns: Optional[PathLike] = None, fast_web_view: Optional[float] = None, plugins: Optional[Iterable[Union[Path, AnyStr]]] = None, plugin_manager=None, keep_temporary_files: Optional[bool] = None, progress_bar: Optional[bool] = None, **kwargs)

Run OCRmyPDF on one PDF or image.

For most arguments, see documentation for the equivalent command line parameter. A few specific arguments are discussed here:

Parameters
  • use_threads – Use worker threads instead of processes. This reduces performance but may make debugging easier since it is easier to set breakpoints.

  • input_file – If a pathlib.Path, str or bytes, this is interpreted as file system path to the input file. If the object appears to be a readable stream (with methods such as .read() and .seek()), the object will be read in its entirety and saved to a temporary file. If input_file is "-", standard input will be read.

  • output_file – If a pathlib.Path, str or bytes, this is interpreted as file system path to the output file. If the object appears to be a writable stream (with methods such as .write() and .seek()), the output will be written to this stream. If output_file is "-", the output will be written to sys.stdout (provided that standard output does not seem to be a terminal device). When a stream is used as output, whether via a writable object or "-", some final validation steps are not performed (we do not read back the stream after it is written).

Raises
  • ocrmypdf.PdfMergeFailedError – If the input PDF is malformed, preventing merging with the OCR layer.

  • ocrmypdf.MissingDependencyError – If a required dependency program is missing or was not found on PATH.

  • ocrmypdf.UnsupportedImageFormatError – If the input file type was an image that could not be read, or some other file type that is not a PDF.

  • ocrmypdf.DpiError – If the input file is an image, but the resolution of the image is not credible (allowing it to proceed would cause poor OCR).

  • ocrmypdf.OutputFileAccessError – If an attempt to write to the intended output file failed.

  • ocrmypdf.PriorOcrFoundError – If the input PDF seems to have OCR or digital text already, and settings did not tell us to proceed.

  • ocrmypdf.InputFileError – Any other problem with the input file.

  • ocrmypdf.SubprocessOutputError – Any error related to executing a subprocess.

  • ocrmypdf.EncryptedPdfError – If the input PDF is encrypted (password protected). OCRmyPDF does not remove passwords.

  • ocrmypdf.TesseractConfigError – If Tesseract reported its configuration was not valid.

Returns

ocrmypdf.ExitCode

class ocrmypdf.Verbosity(value)

Verbosity level for configure_logging.

debug = 1

Output ocrmypdf debug messages

debug_all = 2

More detailed debugging from ocrmypdf and dependent modules

default = 0

Default level of logging

quiet = -1

Suppress most messages

ocrmypdf.configure_logging(verbosity: Verbosity, *, progress_bar_friendly: bool = True, manage_root_logger: bool = False, plugin_manager=None)

Set up logging.

Before calling ocrmypdf.ocr(), you can use this function to configure logging if you want ocrmypdf’s output to look like the ocrmypdf command line interface. It will register log handlers, log filters, and formatters, configure color logging to standard error, and adjust the log levels of third party libraries. Details of this are fine-tuned and subject to change. The verbosity argument is equivalent to the argument --verbose and applies those settings. If you have a wrapper script for ocrmypdf and you want it to be very similar to ocrmypdf, use this function; if you are using ocrmypdf as part of an application that manages its own logging, you probably do not want this function.

If this function is not called, ocrmypdf will not configure logging, and it is up to the caller of ocrmypdf.ocr() to set up logging as it wishes using the Python standard library’s logging module. If this function is called, the caller may of course make further adjustments to logging.

Regardless of whether this function is called, ocrmypdf will perform all of its logging under the "ocrmypdf" logging namespace. In addition, ocrmypdf imports pdfminer, which logs under "pdfminer". A library user may wish to configure both; note that pdfminer is extremely chatty at the log level logging.INFO.

This function does not set up the debug.log log file that the command line interface does at certain verbosity levels. Applications should configure their own debug logging.

Parameters
  • verbosity – Verbosity level.

  • progress_bar_friendly – If True (the default), install a custom log handler that is compatible with progress bars and colored output.

  • manage_root_logger – Configure the process’s root logger.

  • plugin_manager – The plugin manager, used for obtaining the custom log handler.

Returns

The toplevel logger for ocrmypdf (or the root logger, if we are managing it).