ocr/ocr_pyflow

251 lines
10 KiB
Plaintext
Raw Normal View History

2018-10-09 12:43:23 +00:00
#!/usr/bin/env python2.7
# coding=utf-8
2018-10-29 09:38:50 +00:00
2018-10-09 12:43:23 +00:00
"""
ocr_pyflow.py
Usage: For usage instructions run with option --help
2019-01-15 09:46:35 +00:00
Author: Patrick Jentsch <p.jentsch@uni-bielefeld.de>
2018-10-09 12:43:23 +00:00
"""
2018-10-29 09:38:50 +00:00
2018-10-09 12:43:23 +00:00
import argparse
2018-10-29 09:38:50 +00:00
import multiprocessing
2018-10-09 12:43:23 +00:00
import os
import sys
from pyflow import WorkflowRunner
2018-10-29 09:38:50 +00:00
2018-12-18 15:39:33 +00:00
''' TODO:
' Implement --end-page: Last page to ocr
' Implement --memMb: Total amount of memory (RAM) available for this workflow. Default: 2048 * nCores
' Implement --rotate: Rotate pages from input (90, 180, 270)
' Implement --split-pages: Split pages in half after possible rotation
' Implement --start-page: First page to ocr
'''
2018-10-09 12:43:23 +00:00
def parse_arguments():
2018-12-18 15:39:33 +00:00
parser = argparse.ArgumentParser("Performs OCR of (historical) documents utilizing OCRopus for preprocessing and Tesseract OCR \
2018-10-29 09:38:50 +00:00
for OCR. Available outputs are HOCR, PDF, shrinked PDF, and simple DTAbf \
(TEI P5 compliant). Software requirements: imagemagick, ocropus, pdftk, pdftoppm, poppler-utils, pyflow, python2.7, tesseract")
2018-10-09 12:43:23 +00:00
2018-12-18 15:39:33 +00:00
parser.add_argument("-i",
dest="inputDir",
help="Input directory.",
2018-10-09 12:43:23 +00:00
required=True)
2018-12-18 15:39:33 +00:00
parser.add_argument("-l",
dest='lang',
help="Language for OCR",
required=True)
parser.add_argument("-o",
dest="outputDir",
help="Output directory.",
required=True)
parser.add_argument("--keep-intermediates",
2018-10-09 12:43:23 +00:00
action='store_true',
default=False,
2018-12-18 15:39:33 +00:00
dest="keepIntermediates",
help="Keep intermediate files.",
required=False)
parser.add_argument("--nCores",
2018-10-29 09:38:50 +00:00
default=multiprocessing.cpu_count(),
2018-12-18 15:39:33 +00:00
dest="nCores",
help="Total number of cores available.",
2018-10-09 12:43:23 +00:00
required=False,
type=int)
2018-12-18 15:39:33 +00:00
return parser.parse_args()
2018-10-09 12:43:23 +00:00
class OCRWorkflow(WorkflowRunner):
2019-01-15 09:46:35 +00:00
def __init__(self, jobs, keepIntermediates, lang, nCores):
2018-12-18 15:39:33 +00:00
self.jobs = jobs
self.keepIntermediates = keepIntermediates
2019-01-15 09:46:35 +00:00
self.lang = lang
2018-10-09 12:43:23 +00:00
self.nCores = nCores
2018-10-29 09:38:50 +00:00
def workflow(self):
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
# Task "mkdir_job": create output directories
# Dependencies: None
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
mkdir_jobs = []
mkdir_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2018-10-29 09:38:50 +00:00
mkdir_job_number += 1
2019-01-15 09:46:35 +00:00
cmd = 'mkdir -p "%s" "%s" "%s" "%s"' % (
2018-10-29 09:38:50 +00:00
os.path.join(job["output_dir"], "hocr_files"),
os.path.join(job["output_dir"], "tmp", "ocropus-nlbin"),
os.path.join(job["output_dir"], "tmp", "tesseract"),
2019-01-15 09:46:35 +00:00
os.path.join(job["output_dir"], "tmp", "tiff_files")
)
2018-10-29 09:38:50 +00:00
mkdir_jobs.append(self.addTask(label="mkdir_job_-_%i" % (mkdir_job_number), command=cmd))
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
# Task "split_job": split input file into one tiff file per page
# Dependencies: mkdir_jobs
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
split_jobs = []
split_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2018-10-29 09:38:50 +00:00
split_job_number += 1
2019-01-15 09:46:35 +00:00
if job["basename"].endswith(".tif") or job["basename"].endswith(".tiff"):
# TODO: Make the following command work
'''
cmd = 'convert "%s" "%s"' % (
job["path"],
os.path.join(job["output_dir"], "tmp", "tiff_files", os.path.basename(job["path"]).rsplit(".", 1)[0] + "-%sd.tif" % ("%")))
'''
# WORKAROUND
cmd = 'tiff2pdf -o "%s" "%s" && pdftoppm "%s" "%s" -tiff -r 300 -tiffcompression lzw -cropbox && rm "%s"' % (
os.path.join(job["output_dir"], "tmp", "tiff_files", job["basename"].rsplit(".", 1)[0] + ".pdf"),
job["path"],
os.path.join(job["output_dir"], "tmp", "tiff_files", job["basename"].rsplit(".", 1)[0] + ".pdf"),
os.path.join(job["output_dir"], "tmp", "tiff_files", job["basename"].rsplit(".", 1)[0]),
os.path.join(job["output_dir"], "tmp", "tiff_files", job["basename"].rsplit(".", 1)[0] + ".pdf")
)
else:
cmd = 'pdftoppm "%s" "%s" -tiff -r 300 -tiffcompression lzw -cropbox' % (
job["path"],
os.path.join(job["output_dir"], "tmp", "tiff_files", "page")
)
2018-12-18 15:39:33 +00:00
split_jobs.append(self.addTask(label="split_job_-_%i" % (split_job_number), command=cmd, dependencies=mkdir_jobs))
2018-10-29 09:38:50 +00:00
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
# Task "ocropus_nlbin_job": binarize tiff files from previous split
# Dependencies: split_jobs
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
ocropusnlbin_jobs = []
ocropusnlbin_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2018-10-29 09:38:50 +00:00
ocropusnlbin_job_number += 1
2019-01-15 10:13:11 +00:00
cmd = 'ocropus-nlbin -o "%s" "%s"/*' % (
2018-10-29 09:38:50 +00:00
os.path.join(job["output_dir"], "tmp", "ocropus-nlbin"),
2019-01-15 10:13:11 +00:00
os.path.join(job["output_dir"], "tmp", "tiff_files")
2019-01-15 09:46:35 +00:00
)
2018-12-18 15:39:33 +00:00
ocropusnlbin_jobs.append(self.addTask(label="ocropusnlbin_job_-_%i" % (ocropusnlbin_job_number), command=cmd, dependencies=split_jobs))
2018-10-29 09:38:50 +00:00
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
# Task "tesseract_job": perform OCR on binarized images
# Dependencies: ocropusnlbin_jobs
2018-10-09 12:43:23 +00:00
###
self.waitForTasks()
2018-10-29 09:38:50 +00:00
tesseract_jobs = []
tesseract_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2018-10-29 09:38:50 +00:00
# This list is empty if you don't wait for ocropus_nlbin_jobs to complete
for file in filter(lambda x: x.endswith(".bin.png"), os.listdir(os.path.join(job["output_dir"], "tmp", "ocropus-nlbin"))):
tesseract_job_number += 1
2019-01-15 09:46:35 +00:00
cmd = 'tesseract "%s" "%s" -l "%s" hocr pdf txt' % (
2018-10-29 09:38:50 +00:00
os.path.join(job["output_dir"], "tmp", "ocropus-nlbin", file),
os.path.join(job["output_dir"], "tmp", "tesseract", file.rsplit(".", 2)[0]),
2019-01-15 09:46:35 +00:00
self.lang
)
2018-12-18 15:39:33 +00:00
tesseract_jobs.append(self.addTask(label="tesseract_job_-_%i" % (tesseract_job_number), command=cmd, dependencies=ocropusnlbin_jobs, nCores=min(4, self.nCores)))
2018-10-29 09:38:50 +00:00
2018-10-09 12:43:23 +00:00
###
2019-01-15 09:46:35 +00:00
# Task "hocr_to_teip5_job": create TEI P5 file from hocr files
2018-10-29 09:38:50 +00:00
# Dependencies: tesseract_jobs
2018-10-09 12:43:23 +00:00
###
2019-01-15 09:46:35 +00:00
hocr_to_teip5_jobs = []
hocr_to_teip5_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2019-01-15 09:46:35 +00:00
hocr_to_teip5_job_number += 1
cmd = 'parse_hocr "%s" "%s"' % (
os.path.join(job["output_dir"], "tmp", "tesseract"),
os.path.join(job["output_dir"], job["basename"].rsplit(".", 1)[0] + ".xml")
)
hocr_to_teip5_jobs.append(self.addTask(label="hocr_to_teip5_job_-_%i" % (hocr_to_teip5_job_number), command=cmd, dependencies=tesseract_jobs))
2018-11-28 15:49:55 +00:00
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
# Task "move_hocr_job": move hocr files from <output_dir>/tmp/tesseract to <output_dir>/hocr_files
2019-01-15 09:46:35 +00:00
# Dependencies: hocr_to_teip5_jobs
2018-10-09 12:43:23 +00:00
###
2018-10-29 09:38:50 +00:00
move_hocr_jobs = []
move_hocr_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2018-10-29 09:38:50 +00:00
move_hocr_job_number += 1
2019-01-15 09:46:35 +00:00
cmd = 'mv "%s"/*.hocr "%s"' % (
os.path.join(job["output_dir"], "tmp", "tesseract"),
os.path.join(job["output_dir"], "hocr_files")
)
move_hocr_jobs.append(self.addTask(label="move_hocr_job_-_%i" % (move_hocr_job_number), command=cmd, dependencies=hocr_to_teip5_jobs))
2018-10-09 12:43:23 +00:00
2018-10-29 09:38:50 +00:00
###
2019-01-15 09:46:35 +00:00
# Task "pdf_merge_job": Merge PDF files
# Dependencies: tesseract_jobs
###
pdf_merge_jobs = []
pdf_merge_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2019-01-15 09:46:35 +00:00
pdf_merge_job_number += 1
cmd = 'pdftk "%s"/*.pdf cat output "%s"' % (
os.path.join(job["output_dir"], "tmp", "tesseract"),
os.path.join(job["output_dir"], job["basename"].rsplit(".", 1)[0] + ".pdf")
)
pdf_merge_jobs.append(self.addTask(label="pdf_merge_job_-_%i" % (pdf_merge_job_number), command=cmd, dependencies=tesseract_jobs))
2018-10-09 12:43:23 +00:00
2019-01-15 09:46:35 +00:00
###
# Task "pdf_to_txt_job":
# Dependencies: pdf_merge_jobs
###
pdf_to_txt_jobs = []
pdf_to_txt_job_number = 0
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2019-01-15 09:46:35 +00:00
pdf_to_txt_job_number += 1
cmd = 'pdftotext -raw "%s"' % (
os.path.join(job["output_dir"], job["basename"].rsplit(".", 1)[0] + ".pdf")
)
pdf_merge_jobs.append(self.addTask(label="pdf_to_txt_job_-_%i" % (pdf_to_txt_job_number), command=cmd, dependencies=pdf_merge_jobs))
2018-10-09 12:43:23 +00:00
2018-10-29 09:38:50 +00:00
###
# Task "cleanup_job": remove temporary files
2019-01-15 10:06:50 +00:00
# Dependencies: hocr_to_teip5_jobs + move_hocr_jobs + pdf_merge_jobs + pdf_to_txt_jobs
2018-10-29 09:38:50 +00:00
###
cleanup_jobs = []
cleanup_job_counter = 0
2018-12-18 15:39:33 +00:00
if not self.keepIntermediates:
2019-01-15 10:03:09 +00:00
for job in self.jobs:
2018-10-29 09:38:50 +00:00
cleanup_job_counter += 1
2019-01-15 09:46:35 +00:00
cmd = 'rm -r "%s"' % (
os.path.join(job["output_dir"], "tmp")
)
2019-01-15 10:06:50 +00:00
cleanup_jobs.append(self.addTask(label="cleanup_job_-_%i" % (cleanup_job_counter), command=cmd, dependencies=hocr_to_teip5_jobs + move_hocr_jobs + pdf_merge_jobs + pdf_to_txt_jobs))
2018-10-29 09:38:50 +00:00
2019-01-15 09:46:35 +00:00
def analyze_jobs(inputDir, outputDir, level=1):
jobs = []
2018-10-29 09:38:50 +00:00
2019-01-15 09:46:35 +00:00
if level > 2:
return jobs
2018-10-29 09:38:50 +00:00
2019-01-15 09:46:35 +00:00
for file in os.listdir(inputDir):
if os.path.isdir(os.path.join(inputDir, file)):
jobs += analyze_jobs(
os.path.join(inputDir, file),
os.path.join(outputDir, file),
level + 1
)
2019-01-15 10:00:18 +00:00
elif file.endswith(".pdf") or file.endswith(".tif") or file.endswith(".tiff"):
jobs.append({"basename": os.path.basename(file), "output_dir": os.path.join(outputDir, file.rsplit(".", 1)[0]), "path": os.path.join(inputDir, file)})
2018-10-29 09:38:50 +00:00
2019-01-15 09:46:35 +00:00
return jobs
2018-10-09 12:43:23 +00:00
def main():
args = parse_arguments()
2019-01-15 09:46:35 +00:00
wflow = OCRWorkflow(
analyze_jobs(args.inputDir, args.outputDir),
args.keepIntermediates,
args.lang,
args.nCores
)
2018-12-18 15:39:33 +00:00
retval = wflow.run(nCores=args.nCores)
2018-10-09 12:43:23 +00:00
sys.exit(retval)
if __name__ == "__main__":
2019-01-15 09:46:35 +00:00
main()