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.
OCRmyPDF 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 ocrmypdf.ocr('input.pdf', 'output.pdf', deskew=True)
With a few exceptions, all of the command line arguments are available and may be passed as equivalent keywords.
A few differences are that
quiet are not available.
Instead, output should be managed by configuring logging.
Parent process requirements¶
ocrmypdf.ocr() function runs OCRmyPDF similar to command line
execution. To do this, it will:
- create a monitoring thread
- create worker processes (forking itself)
- manage the signal flags of 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. If it is not,
There is no currently no option to manage how jobs are scheduled other
than the argument
jobs= which will limit the number of worker
Forking a child process to call
ocrmypdf.ocr() is suggested. That
way your application will survive and remain interactive even if
OCRmyPDF does not.
OCRmyPDF will log under loggers named
ocrmypdf. In addition, it
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
--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.
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
OCRmyPDF may throw standard Python 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.
ocr(input_file, output_file, *, language=None, image_dpi=None, output_type=None, sidecar=None, jobs=None, use_threads=None, title=None, author=None, subject=None, keywords=None, rotate_pages=None, remove_background=None, deskew=None, clean=None, clean_final=None, unpaper_args=None, oversample=None, remove_vectors=None, threshold=None, force_ocr=None, skip_text=None, redo_ocr=None, skip_big=None, optimize=None, jpg_quality=None, png_quality=None, jbig2_lossy=None, jbig2_page_group_size=None, pages=None, max_image_mpixels=None, tesseract_config=None, tesseract_pagesegmode=None, tesseract_oem=None, pdf_renderer=None, tesseract_timeout=None, rotate_pages_threshold=None, pdfa_image_compression=None, user_words=None, user_patterns=None, fast_web_view=None, keep_temporary_files=None, progress_bar=None, tesseract_env=None)¶
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:
- use_threads (bool) – Use worker threads instead of processes. This reduces performance but may make debugging easier since it is easier to set breakpoints.
- tesseract_env (dict) – Override environment variables for Tesseract
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.
Verbosity level for configure_logging.
Output ocrmypdf debug messages
More detailed debugging from ocrmypdf and dependent modules
Default level of logging
Suppress most messages
configure_logging(verbosity, progress_bar_friendly=True, manage_root_logger=False)¶
Set up logging.
Library users may wish to use this function if they want their log output to be similar to ocrmypdf command line interface. If not used, the external application should configure logging on its own.
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
Library users may perform additional configuration afterwards.
- verbosity (Verbosity) – Verbosity level.
- progress_bar_friendly (bool) – Install the TqdmConsole log handler, which is compatible with the tqdm progress bar; without this log messages will overwrite the progress bar
- manage_root_logger (bool) – Configure the process’s root logger, to ensure all log output is sent through