ocr/ocr

496 lines
22 KiB
Python
Executable File

#!/usr/bin/env python2.7
# coding=utf-8
"""
ocr
Usage: For usage instructions run with option --help
Author: Patrick Jentsch <p.jentsch@uni-bielefeld.de>
"""
from argparse import ArgumentParser
from pyflow import WorkflowRunner
import multiprocessing
import os
import re
import sys
TESSERACT_MODELS = ['deu', 'eng', 'enm', 'fra', 'frk', 'frm', 'ita', 'por',
'spa']
def parse_args():
parser = ArgumentParser(description='OCR Pipeline utilizing tesseract.')
parser.add_argument('-i', '--input-directory',
help='Input directory (only PDF files get processed)',
required=True)
parser.add_argument('-o', '--output-directory',
help='Output directory',
required=True)
parser.add_argument('-l', '--language',
choices=TESSERACT_MODELS,
required=True)
parser.add_argument('--binarize',
action='store_true',
help='Use ocropy binarisation as preprocessing step.')
parser.add_argument('--compress',
action='store_true',
help='Compress the final PDF result file.')
parser.add_argument('--log-dir')
parser.add_argument('--n-cores',
default=min(4, multiprocessing.cpu_count()),
help='Total number of cores available.',
type=int)
parser.add_argument('--zip',
help='Zips all results in different archives depending'
' on result types. Also zips everything into one '
'archive.')
return parser.parse_args()
class OCRPipelineJob:
def __init__(self, file, output_dir):
self.file = file
self.name = os.path.basename(file).rsplit('.', 1)[0]
self.output_dir = output_dir
class OCRPipeline(WorkflowRunner):
def __init__(self, binarize, jobs, lang, n_cores, output_dir, zip,
compress):
self.binarize = binarize
self.jobs = jobs
self.lang = lang
self.n_cores = n_cores
self.output_dir = output_dir
self.zip = zip
self.compress = compress
def workflow(self):
if not self.jobs:
return
'''
' ##################################################
' # setup output directory #
' ##################################################
'''
setup_output_directory_jobs = []
for i, job in enumerate(self.jobs):
intermediate_dir = os.path.join(job.output_dir, 'tmp')
cmd = 'mkdir'
cmd += ' -p'
cmd += ' "{}"'.format(intermediate_dir)
cmd += ' "{}"'.format(os.path.join(job.output_dir, 'poco'))
lbl = 'setup_output_directory_-_{}'.format(i)
setup_output_directory_jobs.append(self.addTask(command=cmd,
label=lbl))
'''
' ##################################################
' # split input #
' ##################################################
'''
split_input_jobs = []
n_cores = min(self.n_cores, max(1, int(self.n_cores / len(self.jobs))))
for i, job in enumerate(self.jobs):
output_dir = os.path.join(job.output_dir, 'tmp')
cmd = 'gs'
cmd += ' -dBATCH'
cmd += ' -dNOPAUSE'
cmd += ' -dNumRenderingThreads={}'.format(n_cores)
cmd += ' -dQUIET'
cmd += ' -r300'
cmd += ' -sDEVICE=tiff24nc'
cmd += ' -sCompression=lzw'
cmd += ' "-sOutputFile={}/page-%d.tif"'.format(output_dir)
cmd += ' "{}"'.format(job.file)
deps = 'setup_output_directory_-_{}'.format(i)
lbl = 'split_input_-_{}'.format(i)
split_input_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl,
nCores=n_cores))
if self.binarize:
'''
' The binarization_jobs list is created based on the output files
' of the split_jobs. So wait until they are finished.
'''
self.waitForTasks()
'''
' ##################################################
' # binarization #
' ##################################################
'''
binarization_jobs = []
'''
' We run ocropus-nlbin with either four or, if there are less then
' four cores available for this workflow, the available core
' number.
'''
n_cores = min(4, self.n_cores)
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
output_dir = input_dir
files = filter(lambda x: x.endswith('.tif'),
os.listdir(input_dir))
files.sort(key=lambda x: int(re.search(r'\d+', x).group(0)))
files = map(lambda x: os.path.join(input_dir, x), files)
cmd = 'ocropus-nlbin "{}"'.format('" "'.join(files))
cmd += ' --nocheck'
cmd += ' --output "{}"'.format(output_dir)
cmd += ' --parallel "{}"'.format(n_cores)
deps = 'split_input_-_{}'.format(i)
lbl = 'binarization_-_{}'.format(i)
binarization_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl,
nCores=n_cores))
'''
' The post_binarization_jobs are created based on the output files
' of the binarization_jobs. So wait until they are finished.
'''
self.waitForTasks()
'''
' ##################################################
' # post binarization #
' ##################################################
'''
post_binarization_jobs = []
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
output_dir = input_dir
number = 0
files = filter(lambda x: x.endswith('.bin.png'),
os.listdir(input_dir))
files.sort()
for file in files:
# int conversion is done in order to trim leading zeros
output_file = os.path.join(output_dir, 'page-{}.bin.png'.format(int(file.split('.', 1)[0]))) # noqa
cmd = 'mv "{}" "{}"'.format(os.path.join(output_dir, file),
output_file)
deps = 'binarization_-_{}'.format(i)
lbl = 'post_binarization_-_{}-{}'.format(i, number)
post_binarization_jobs.append(
self.addTask(command=cmd, dependencies=deps, label=lbl)
)
number += 1
'''
' The ocr_jobs are created based of the output files of either the
' split_jobs or post_binarization_jobs. So wait until they are
' finished.
'''
self.waitForTasks()
'''
' ##################################################
' # ocr #
' ##################################################
'''
ocr_jobs = []
'''
' Tesseract runs fastest with four cores. So we run it with either four
' or, if there are less then four cores available for this workflow,
' the available core number.
'''
n_cores = min(4, self.n_cores)
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
output_dir = input_dir
files = filter(lambda x: x.endswith('.bin.png' if self.binarize else '.tif'), os.listdir(input_dir)) # noqa
files.sort(key=lambda x: int(re.search(r'\d+', x).group(0)))
files = map(lambda x: os.path.join(input_dir, x), files)
number = 0
for file in files:
output_file_base = os.path.join(output_dir, file.rsplit('.', 2 if self.binarize else 1)[0]) # noqa
cmd = 'tesseract "{}" "{}"'.format(file, output_file_base)
cmd += ' -l "{}"'.format(self.lang)
cmd += ' hocr pdf txt'
cmd += ' && '
cmd += 'sed -i \'s+{}/++g\' "{}".hocr'.format(input_dir, output_file_base) # noqa
if self.binarize:
deps = 'post_binarization_-_{}-{}'.format(i, number)
else:
deps = 'split_input_-_{}'.format(i)
label = 'ocr_-_{}-{}'.format(i, number)
ocr_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=label,
nCores=n_cores))
number += 1
'''
' The following jobs are created based of the output files of the
' ocr_jobs. So wait until they are finished.
'''
self.waitForTasks()
'''
' ##################################################
' # combined pdf creation #
' ##################################################
'''
combined_pdf_creation_jobs = []
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
files = filter(lambda x: x.endswith('.pdf'),
os.listdir(input_dir))
files.sort(key=lambda x: int(re.search(r'\d+', x).group(0)))
files = map(lambda x: os.path.join(input_dir, x), files)
output_file = os.path.join(job.output_dir,
'{}.pdf'.format(job.name))
cmd = 'pdfunite "{}" "{}"'.format('" "'.join(files), output_file)
deps = filter(lambda x: x.startswith('ocr_-_{}'.format(i)),
ocr_jobs)
lbl = 'combined_pdf_creation_-_{}'.format(i)
combined_pdf_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
'''
' ##################################################
' # combined txt creation #
' ##################################################
'''
combined_txt_creation_jobs = []
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
files = filter(lambda x: x.endswith('.txt'), os.listdir(input_dir))
files.sort(key=lambda x: int(re.search(r'\d+', x).group(0)))
files = map(lambda x: os.path.join(input_dir, x), files)
output_file = os.path.join(job.output_dir, '{}.txt'.format(job.name)) # noqa
cmd = 'cat "{}" > "{}"'.format('" "'.join(files), output_file)
deps = filter(lambda x: x.startswith('ocr_-_{}'.format(i)),
ocr_jobs)
lbl = 'combined_txt_creation_-_{}'.format(i)
combined_txt_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
'''
' ##################################################
' # tei p5 creation #
' ##################################################
'''
tei_p5_creation_jobs = []
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
files = filter(lambda x: x.endswith('.hocr'), os.listdir(input_dir)) # noqa
files.sort(key=lambda x: int(re.search(r'\d+', x).group(0)))
files = map(lambda x: os.path.join(input_dir, x), files)
output_file = os.path.join(job.output_dir, '{}.xml'.format(job.name)) # noqa
cmd = 'hocrtotei "{}" "{}"'.format('" "'.join(files), output_file)
deps = filter(lambda x: x.startswith('ocr_-_{}'.format(i)),
ocr_jobs)
lbl = 'tei_p5_creation_-_{}'.format(i)
tei_p5_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
'''
' ##################################################
' # poco bundle creation #
' ##################################################
'''
poco_bundle_creation_jobs = []
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
output_dir = os.path.join(job.output_dir, 'poco')
cmd = 'mv "{}"/*.hocr "{}"'.format(input_dir, output_dir)
cmd += ' && '
cmd += 'mv "{}"/*.{} "{}"'.format(input_dir, 'bin.png' if self.binarize else 'tif', output_dir) # noqa
deps = filter(lambda x: x.startswith('ocr_-_{}'.format(i)),
ocr_jobs)
deps.append('tei_p5_creation_-_{}'.format(i))
lbl = 'poco_bundle_creation_-_{}'.format(i)
poco_bundle_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
'''
' The following jobs are created based of the output files of the
' combined_pdf_creation_jobs. So wait until they are finished.
'''
self.waitForTasks()
'''
' ##################################################
' # pdf compression #
' ##################################################
'''
pdf_compression_jobs = []
n_cores = min(self.n_cores, max(1, int(self.n_cores / len(self.jobs))))
if self.compress:
for i, job in enumerate(self.jobs):
file = filter(lambda x: x.endswith('.pdf'), os.listdir(job.output_dir))[0] # noqa
original_file = os.path.join(job.output_dir, file)
compressed_file = os.path.join(job.output_dir, 'c_' + file)
cmd = 'gs'
cmd += ' -dBATCH'
cmd += ' -dNOPAUSE'
cmd += ' -dNumRenderingThreads={}'.format(n_cores)
cmd += ' -dPDFSETTINGS=/ebook'
# -dCompatibilityLevel must be defined after -dPDFSETTINGS
cmd += ' -dCompatibilityLevel=1.4'
cmd += ' -dQUIET'
cmd += ' -sDEVICE=pdfwrite'
cmd += ' "-sOutputFile={}"'.format(compressed_file)
cmd += ' "{}"'.format(original_file)
cmd += ' && '
cmd += 'mv "{}" "{}"'.format(compressed_file, original_file)
deps = 'combined_pdf_creation_-_{}'.format(i)
lbl = 'pdf_compression_-_{}'.format(i)
pdf_compression_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl,
nCores=n_cores))
'''
' ##################################################
' # cleanup #
' ##################################################
'''
cleanup_jobs = []
for i, job in enumerate(self.jobs):
input_dir = os.path.join(job.output_dir, 'tmp')
cmd = 'rm -r "{}"'.format(input_dir)
if self.compress:
deps = ['pdf_compression_-_{}'.format(i)]
else:
deps = ['combined_pdf_creation_-_{}'.format(i)]
deps.append('combined_txt_creation_-_{}'.format(i))
deps.append('poco_bundle_creation_-_{}'.format(i))
deps.append('tei_p5_creation_-_{}'.format(i))
lbl = 'cleanup_-_{}'.format(i)
cleanup_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
'''
' ##################################################
' # zip creation #
' ##################################################
'''
zip_creation_jobs = []
if self.zip is not None:
# Remove .zip file extension if provided
if self.zip.endswith('.zip'):
self.zip = self.zip[:-4]
self.zip = self.zip if self.zip else 'output'
# zip all files
cmd = 'cd "{}"'.format(self.output_dir)
cmd += ' && '
cmd += 'zip'
cmd += ' -r'
cmd += ' "{}".all.zip .'.format(self.zip)
cmd += ' -x "pyflow.data*" "*tmp*"'
cmd += ' -i "*.pdf" "*.txt" "*.xml" "*.hocr" "*.{}"'.format('bin.png' if self.binarize else 'tif') # noqa
cmd += ' && '
cmd += 'cd -'
deps = (pdf_compression_jobs if self.compress else
combined_pdf_creation_jobs)
deps += combined_txt_creation_jobs
deps += poco_bundle_creation_jobs
lbl = 'zip_creation_-_all'
zip_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
# zip PDF files
cmd = 'cd "{}"'.format(self.output_dir)
cmd += ' && '
cmd += 'zip'
cmd += ' -r'
cmd += ' "{}".pdf.zip .'.format(self.zip)
cmd += ' -x "pyflow.data*" "*tmp*"'
cmd += ' -i "*.pdf"'
cmd += ' && '
cmd += 'cd -'
deps = (pdf_compression_jobs if self.compress else
combined_pdf_creation_jobs)
lbl = 'zip_creation_-_pdf'
zip_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
# zip TXT files
cmd = 'cd "{}"'.format(self.output_dir)
cmd += ' && '
cmd += 'zip'
cmd += ' -r'
cmd += ' "{}".txt.zip .'.format(self.zip)
cmd += ' -x "pyflow.data*" "*tmp*"'
cmd += ' -i "*.txt"'
cmd += ' && '
cmd += 'cd -'
deps = combined_txt_creation_jobs
lbl = 'zip_creation_-_txt'
zip_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
# zip XML files
cmd = 'cd "{}"'.format(self.output_dir)
cmd += ' && '
cmd += 'zip'
cmd += ' -r'
cmd += ' "{}".xml.zip .'.format(self.zip)
cmd += ' -x "pyflow.data*" "*tmp*"'
cmd += ' -i "*.xml"'
cmd += ' && '
cmd += 'cd -'
deps = tei_p5_creation_jobs
lbl = 'zip_creation_-_xml'
zip_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
# zip PoCo bundles
cmd = 'cd "{}"'.format(self.output_dir)
cmd += ' && '
cmd += 'zip'
cmd += ' -r'
cmd += ' "{}".poco.zip .'.format(self.zip)
cmd += ' -x "pyflow.data*" "*tmp*"'
cmd += ' -i "*.hocr" "*.{}"'.format('bin.png' if self.binarize else 'tif') # noqa
cmd += ' && '
cmd += 'cd -'
deps = poco_bundle_creation_jobs
lbl = 'zip_creation_-_poco'
zip_creation_jobs.append(self.addTask(command=cmd,
dependencies=deps,
label=lbl))
def collect_jobs(input_dir, output_dir):
jobs = []
for file in os.listdir(input_dir):
if os.path.isdir(os.path.join(input_dir, file)):
jobs += collect_jobs(os.path.join(input_dir, file),
os.path.join(output_dir, file))
elif file.endswith('.pdf'):
jobs.append(OCRPipelineJob(os.path.join(input_dir, file),
os.path.join(output_dir, file)))
return jobs
def main():
args = parse_args()
jobs = collect_jobs(args.input_directory, args.output_directory)
ocr_pipeline = OCRPipeline(args.binarize, jobs, args.language,
args.n_cores, args.output_directory, args.zip,
args.compress)
retval = ocr_pipeline.run(
dataDirRoot=(args.log_dir or args.output_directory),
nCores=args.n_cores
)
sys.exit(retval)
if __name__ == '__main__':
main()