diff --git a/ocrmypdf/main.py b/ocrmypdf/main.py index 06be17d9..9be6eb1c 100755 --- a/ocrmypdf/main.py +++ b/ocrmypdf/main.py @@ -188,6 +188,10 @@ advanced.add_argument( '--tesseract-timeout', default=180.0, type=float, metavar='SECONDS', help='give up on OCR after the timeout, but copy the preprocessed page ' 'into the final output') +advanced.add_argument( + '--rotate-pages-threshold', default=14.0, type=float, metavar='CONFIDENCE', + help="only rotate pages when confidence is above this value (arbitrary " + "units reported by tesseract)") debugging = parser.add_argument_group( "Debugging", @@ -534,15 +538,29 @@ def orient_page( 270: '⇦' } + apply_correction = False + description = '' + if orient_conf.confidence >= options.rotate_pages_threshold: + if orient_conf.angle != 0: + apply_correction = True + description = ' - will rotate' + else: + description = ' - rotation appears correct' + else: + if orient_conf.angle != 0: + description = ' - confidence too low to rotate' + else: + description = ' - no change' + log.info( '{0:4d}: page is facing {1}, confidence {2:.2f}{3}'.format( page_number(preview), direction.get(orient_conf.angle, '?'), orient_conf.confidence, - ' - correcting rotation' if orient_conf.angle != 0 else '') + description) ) - if orient_conf.angle == 0: + if not apply_correction: re_symlink(page_pdf, output_file) else: writer = pypdf.PdfFileWriter() diff --git a/tests/test_main.py b/tests/test_main.py index ba06b629..f5383a72 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -343,6 +343,36 @@ def test_autorotate(spoof_tesseract_cache, renderer): assert correlation > 0.80 +def test_autorotate_threshold_low(spoof_tesseract_cache): + out = check_ocrmypdf('cardinal.pdf', 'test_autorotate_threshold.pdf', + '--rotate-pages-threshold', '1', + '-r', '-v', '1', env=spoof_tesseract_cache) + + # Low threshold -> always rotate -> expect high correlation between + # reference page and test page + correlation = check_monochrome_correlation( + reference_pdf=_infile('cardinal.pdf'), + reference_pageno=1, + test_pdf=out, + test_pageno=3) + assert correlation > 0.80 + + +def test_autorotate_threshold_high(spoof_tesseract_cache): + out = check_ocrmypdf('cardinal.pdf', 'test_autorotate_threshold.pdf', + '--rotate-pages-threshold', '99', + '-r', '-v', '1', env=spoof_tesseract_cache) + + # High threshold -> never rotate -> expect low correlation since + # test page will not be rotated + correlation = check_monochrome_correlation( + reference_pdf=_infile('cardinal.pdf'), + reference_pageno=1, + test_pdf=out, + test_pageno=3) + assert correlation < 0.10 + + @pytest.mark.parametrize('renderer', [ 'hocr', 'tesseract',