1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
|
import errno
import os
import subprocess
from io import StringIO
from tempfile import TemporaryDirectory
from unittest.mock import patch, MagicMock
from PIL import Image
from pyocr import builders
from pyocr import tesseract
from .test_base import BaseTest
class TestTesseract(BaseTest):
"""
These tests make sure the requirements for the tests are met.
"""
def setUp(self):
super().setUp()
self.stdout = MagicMock()
self.image = Image.new(mode="RGB", size=(1, 1))
self.message = (
b"tesseract 4.0.0\n leptonica-1.76.0\n"
b" libgif 5.1.4 : libjpeg 6b (libjpeg-turbo 1.5.2)"
b" : libpng 1.6.34 "
b": libtiff 4.0.9 : zlib 1.2.11 : libwebp 0.6.1"
b" : libopenjp2 2.3.0\n"
b" Found AVX2\n Found AVX\n Found SSE\n"
)
self.stdout.stdout.read.return_value = self.message
self.stdout.wait.return_value = 0
@patch("shutil.which")
def test_available(self, which):
which.return_value = True
self.assertTrue(tesseract.is_available())
which.assert_called_once_with("tesseract")
@patch("subprocess.Popen")
def test_version_error(self, popen):
tesseract.g_version = None # drop cached version
self.stdout.wait.return_value = 2
popen.return_value = self.stdout
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.get_version()
self.assertEqual(te.exception.status, 2)
self.assertEqual(te.exception.message, self.message.decode())
@patch("subprocess.Popen")
def test_version_tesseract4(self, popen):
tesseract.g_version = None # drop cached version
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (4, 0, 0))
# stderr must be explicitely ignored when calling 'tesseract -v'.
# See https://gitlab.gnome.org/World/OpenPaperwork/pyocr/-/issues/118
popen.assert_called_once()
(args, kwargs) = popen.call_args
self.assertNotIn('stderr', kwargs)
@patch("subprocess.Popen")
def test_version_tesseract4dev(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract 4.00.00dev2")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (4, 0, 0))
@patch("subprocess.Popen")
def test_version_tesseract4alpha(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract 4.00.00alpha")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (4, 0, 0))
@patch("subprocess.Popen")
def test_version_tesseract3(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract 3.05")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (3, 5, 0))
@patch("subprocess.Popen")
def test_version_tesseract3_no_minor(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract 3.0")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (3, 0, 0))
@patch("subprocess.Popen")
def test_version_windows(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract v4.0.0.20181030")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (4, 0, 0))
@patch("subprocess.Popen")
def test_version_cache(self, popen):
"""
Make sure Tesseract is not called everytime we need the version.
We need the version *often* in the code, and calling Tesseract
everytime wouldn't be wise.
"""
tesseract.g_version = None # drop cached version
self.stdout.stdout.read.return_value = self.message
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (4, 0, 0))
self.stdout.stdout.read.return_value = "garbage"
popen.return_value = self.stdout
self.assertSequenceEqual(tesseract.get_version(), (4, 0, 0))
@patch("subprocess.Popen")
def test_version_error_splitting(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract 3")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.get_version()
self.assertEqual(te.exception.status, 0)
self.assertIn("Unable to parse Tesseract version (spliting failed): ",
te.exception.message)
@patch("subprocess.Popen")
def test_version_error_nan(self, popen):
tesseract.g_version = None # drop cached version
message = self.message.replace(b"tesseract 4.0.0",
b"tesseract A.B.C")
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.get_version()
self.assertEqual(te.exception.status, 0)
self.assertIn("Unable to parse Tesseract version (not a number): ",
te.exception.message)
@patch("subprocess.Popen")
def test_langs(self, popen):
self.stdout.stdout.read.return_value = (
b"List of available languages (4):\n"
b"eng\n"
b"fra\n"
b"jpn\n"
b"osd\n"
)
popen.return_value = self.stdout
langs = tesseract.get_available_languages()
for lang in ("eng", "fra", "jpn", "osd"):
self.assertIn(lang, langs)
popen.assert_called_once_with(
["tesseract", "--list-langs"],
startupinfo=None, creationflags=0,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
@patch("subprocess.Popen")
def test_langs_error(self, popen):
self.stdout.stdout.read.return_value = b"No languages\n"
self.stdout.wait.return_value = 1
popen.return_value = self.stdout
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.get_available_languages()
self.assertEqual(te.exception.status, 1)
self.assertEqual("unable to get languages", te.exception.message)
popen.assert_called_once_with(
["tesseract", "--list-langs"],
startupinfo=None, creationflags=0,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
@patch("pyocr.tesseract.get_available_languages")
@patch("pyocr.tesseract.get_version")
def test_can_detect_orientation_tesseract4(self, get_version,
get_available_languages):
get_version.return_value = (4, 0, 0)
get_available_languages.return_value = ['eng', 'fra', 'jpn', 'osd']
self.assertTrue(tesseract.can_detect_orientation())
get_available_languages.return_value = ['eng', 'fra', 'jpn']
self.assertFalse(tesseract.can_detect_orientation())
@patch("pyocr.tesseract.get_available_languages")
@patch("pyocr.tesseract.get_version")
def test_can_detect_orientation_tesseract3(
self, get_version, get_available_languages
):
get_available_languages.return_value = ['eng', 'fra', 'jpn', 'osd']
get_version.return_value = (3, 3, 0)
self.assertTrue(tesseract.can_detect_orientation())
@patch("pyocr.tesseract.get_available_languages")
@patch("pyocr.tesseract.get_version")
def test_cannot_detect_orientation_tesseract3(
self, get_version, get_available_languages
):
get_available_languages.return_value = ['eng', 'fra', 'jpn', 'osd']
get_version.return_value = (3, 2, 1)
self.assertFalse(tesseract.can_detect_orientation())
def test_name(self):
self.assertEqual(tesseract.get_name(), "Tesseract (sh)")
@patch("pyocr.tesseract.get_version")
def test_psm_parameter(self, get_version):
get_version.return_value = (3, 5, 0)
self.assertEqual(tesseract.psm_parameter(), "-psm")
get_version.return_value = (4, 0, 0)
self.assertEqual(tesseract.psm_parameter(), "--psm")
def test_available_builders(self):
self.assertListEqual(
tesseract.get_available_builders(),
[
builders.LineBoxBuilder,
builders.TextBuilder,
builders.WordBoxBuilder,
tesseract.CharBoxBuilder,
builders.DigitBuilder,
builders.DigitLineBoxBuilder,
]
)
@patch("pyocr.tesseract.get_version")
@patch("subprocess.Popen")
def test_run_tesseract(self, popen, get_version):
message = (
b"Tesseract Open Source OCR Engine v4.0.0 with Leptonica\n"
)
self.stdout.stdout.read.return_value = message
popen.return_value = self.stdout
with TemporaryDirectory() as tmpdir:
self.image.save(os.path.join(tmpdir, "input.bmp"))
status, error = tesseract.run_tesseract(
"input.bmp",
"output",
cwd=tmpdir,
)
self.assertEqual(status, 0)
self.assertEqual(error, message)
popen.assert_called_once_with(
["tesseract", "input.bmp", "output"],
cwd=tmpdir,
startupinfo=None,
creationflags=0,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
get_version.return_value = (4, 0, 0)
builder = builders.TextBuilder()
with TemporaryDirectory() as tmpdir:
self.image.save(os.path.join(tmpdir, "input2.bmp"))
status, error = tesseract.run_tesseract(
"input2.bmp",
"output2",
cwd=tmpdir,
lang="fra",
flags=builder.tesseract_flags,
configs=builder.tesseract_configs,
)
self.assertEqual(status, 0)
self.assertEqual(error, message)
popen.assert_called_with(
["tesseract", "input2.bmp", "output2", "-l", "fra", "--psm", "3"],
cwd=tmpdir,
startupinfo=None,
creationflags=0,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
self.assertEqual(popen.call_count, 2)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract4(self, popen, temp_dir, get_version):
get_version.return_value = (4, 0, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: 90\n"
b"Rotate: 270\n"
b"Orientation confidence: 9.30\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.detect_orientation(self.image)
self.assertEqual(result["angle"], 90)
self.assertEqual(result["confidence"], 9.30)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "--psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract4_non_rgb_image(self, popen, temp_dir,
get_version):
"""This tests that detect_orientation works with non RGB mode images
and that image is converted in function."""
image = self.image.convert("L")
get_version.return_value = (4, 0, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: 90\n"
b"Rotate: 270\n"
b"Orientation confidence: 9.30\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.detect_orientation(image)
self.assertEqual(result["angle"], 90)
self.assertEqual(result["confidence"], 9.30)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "--psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract4_with_lang(self, popen, temp_dir,
get_version):
get_version.return_value = (4, 0, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: 90\n"
b"Rotate: 270\n"
b"Orientation confidence: 9.30\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.detect_orientation(self.image, lang="fra")
self.assertEqual(result["angle"], 90)
self.assertEqual(result["confidence"], 9.30)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout",
"--psm", "0", "-l", "osd"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract4_error(self, popen, temp_dir,
get_version):
get_version.return_value = (4, 0, 0)
self.stdout.stdout.read.return_value = (
b"Could not initialize tesseract\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.detect_orientation(self.image)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "--psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
self.assertEqual(te.exception.status, -1)
self.assertIn("Error initializing tesseract", te.exception.message)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract4_bad_output(self, popen, temp_dir,
get_version):
get_version.return_value = (4, 0, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: ABC\n"
b"Rotate: 270\n"
b"Orientation confidence: AB.CD\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.detect_orientation(self.image)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "--psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
self.assertEqual(te.exception.status, -1)
self.assertIn("No script found in image", te.exception.message)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract3(self, popen, temp_dir, get_version):
get_version.return_value = (3, 5, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: 90\n"
b"Rotate: 270\n"
b"Orientation confidence: 9.30\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.detect_orientation(self.image)
self.assertEqual(result["angle"], 90)
self.assertEqual(result["confidence"], 9.30)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "-psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract3_with_lang(self, popen, temp_dir,
get_version):
get_version.return_value = (3, 5, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: 90\n"
b"Rotate: 270\n"
b"Orientation confidence: 9.30\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.detect_orientation(self.image, lang="fra")
self.assertEqual(result["angle"], 90)
self.assertEqual(result["confidence"], 9.30)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "-psm", "0", "-l", "fra"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract3_error(self, popen, temp_dir,
get_version):
get_version.return_value = (3, 5, 0)
self.stdout.stdout.read.return_value = (
b"Could not initialize tesseract\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.detect_orientation(self.image)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "-psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
self.assertEqual(te.exception.status, -1)
self.assertIn("Error initializing tesseract", te.exception.message)
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("subprocess.Popen")
def test_detect_orientation_tesseract3_bad_output(self, popen, temp_dir,
get_version):
get_version.return_value = (3, 5, 0)
self.stdout.stdout.read.return_value = (
b"Page number: 0\n"
b"Orientation in degrees: ABC\n"
b"Rotate: 270\n"
b"Orientation confidence: AB.CD\n"
b"Script: Latin\n"
b"Script confidence: 8.06\n"
)
popen.return_value = self.stdout
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.detect_orientation(self.image)
popen.assert_called_once_with(
["tesseract", "input.bmp", "stdout", "-psm", "0"],
stdin=subprocess.PIPE,
shell=False,
startupinfo=None,
creationflags=0,
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
self.assertEqual(te.exception.status, -1)
self.assertIn("No script found in image", te.exception.message)
class TestTesseractTxt(BaseTest):
"""
These tests make sure the "usual" OCR works fine. (the one generating
a .txt file)
"""
@patch("pyocr.tesseract.get_version")
def setUp(self, get_version):
super().setUp()
get_version.return_value = (4, 0, 0)
self.image = Image.new(mode="RGB", size=(1, 1))
self.builder = builders.TextBuilder()
@patch("pyocr.tesseract.get_version")
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_image_to_string_defaults_to_text_buidler(self, run_tesseract,
copen, temp_dir,
get_version):
get_version.return_value = (4, 0, 0)
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("text"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.image_to_string(self.image)
self.assertEqual(result, self._get_file_content("text").strip())
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_lang(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("text"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.image_to_string(self.image, lang="fra",
builder=self.builder)
self.assertEqual(result, self._get_file_content("text").strip())
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang="fra",
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_text(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("text"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.image_to_string(self.image,
builder=self.builder)
self.assertEqual(result, self._get_file_content("text").strip())
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_text_non_rgb_image(self, run_tesseract, copen, temp_dir):
"""This tests that image_to_string works with non RGB mode images and
that image is converted in function."""
image = self.image.convert("L")
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("text"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.image_to_string(image, builder=self.builder)
self.assertEqual(result, self._get_file_content("text").strip())
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_text_error(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (1, "Error")
copen.return_value = StringIO(self._get_file_content("text"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, 1)
self.assertEqual(te.exception.message, "Error")
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_text_error_file(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.side_effect = Exception("Unknown error")
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(Exception):
tesseract.image_to_string(self.image, builder=self.builder)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_text_cannot_open_file(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.side_effect = PermissionError(errno.EPERM, "Error opening file")
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(PermissionError):
tesseract.image_to_string(self.image, builder=self.builder)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_text_no_output(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "No file output")
copen.side_effect = FileNotFoundError(
errno.ENOENT,
"[Errno 2] No such file or directory: 'output'"
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, -1)
self.assertIn("Unable to find output file (tested",
te.exception.message)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
class TestTesseractCharBox(BaseTest):
"""
These tests make sure that Tesseract box handling works fine.
"""
@patch("pyocr.tesseract.get_version")
def setUp(self, get_version):
super().setUp()
get_version.return_value = (4, 0, 0)
self.image = Image.new(mode="RGB", size=(1, 1))
self.builder = tesseract.CharBoxBuilder()
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_char(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("boxes"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
result = tesseract.image_to_string(self.image,
builder=self.builder)
for box in result:
self.assertIsInstance(box, builders.Box)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_char_error(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (1, "Error")
copen.return_value = StringIO(self._get_file_content("boxes"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, 1)
self.assertEqual(te.exception.message, "Error")
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_char_no_output(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "No file output")
copen.side_effect = FileNotFoundError(
errno.ENOENT,
"[Errno 2] No such file or directory: 'output'"
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, -1)
self.assertIn("Unable to find output file (tested",
te.exception.message)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
class TestCharBoxBuilder(BaseTest):
def test_init(self):
builder = tesseract.CharBoxBuilder()
self.assertListEqual(builder.file_extensions, ["box"])
self.assertListEqual(builder.tesseract_flags, [])
self.assertListEqual(
builder.tesseract_configs,
["batch.nochop", "makebox"]
)
self.assertListEqual(builder.cuneiform_args, [])
self.assertEqual(builder.tesseract_layout, 1)
def test_read_file(self):
builder = tesseract.CharBoxBuilder()
boxes = builder.read_file(self._get_file_handle("boxes"))
for box in boxes:
self.assertIsInstance(box, builders.Box)
def test_read_empty_file(self):
builder = tesseract.CharBoxBuilder()
output = StringIO()
self.assertListEqual(builder.read_file(output), [])
def test_read_file_empty_lines(self):
builder = tesseract.CharBoxBuilder()
boxes = builder.read_file(self._get_file_handle("boxes_empty_lines"))
for box in boxes:
self.assertIsInstance(box, builders.Box)
self.assertNotEqual(box.content, "")
def test_read_file_short_lines(self):
builder = tesseract.CharBoxBuilder()
boxes = builder.read_file(self._get_file_handle("boxes_short_lines"))
for box in boxes:
self.assertIsInstance(box, builders.Box)
self.assertNotEqual(box.content, "#")
def test_write_file(self):
builder = tesseract.CharBoxBuilder()
output = StringIO()
boxes = [
builders.Box("a", ((10, 11), (12, 13)), 95),
builders.Box("b", ((11, 12), (13, 14))),
builders.Box("c", ((12, 13), (14, 15))),
builders.Box("d", ((13, 14), (15, 16)), 87),
builders.Box("\xe9", ((14, 15), (16, 17)), 88),
]
builder.write_file(output, boxes)
output.seek(0)
output = output.read()
for box in boxes:
self.assertIn(box.content, output)
self.assertIn("{} {} {} {}".format(
box.position[0][0], box.position[0][1],
box.position[1][0], box.position[1][1],
), output)
def test_str_method(self):
self.assertEqual(str(tesseract.CharBoxBuilder()), "Character boxes")
class TestTesseractDigits(BaseTest):
@patch("pyocr.tesseract.get_version")
def setUp(self, get_version):
super().setUp()
get_version.return_value = (4, 0, 0)
self.builder = builders.DigitBuilder()
self.image = Image.new(mode="RGB", size=(1, 1))
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_digits(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("digits"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with open(os.path.join(tmpdir, "output.txt"), "w") as fh:
fh.write("")
result = tesseract.image_to_string(self.image,
builder=self.builder)
for digit in result:
self.assertIsInstance(int(digit), int)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
class TestTesseractWordBox(BaseTest):
@patch("pyocr.tesseract.get_version")
def setUp(self, get_version):
super().setUp()
get_version.return_value = (4, 0, 0)
self.image = Image.new(mode="RGB", size=(1, 1))
self.builder = builders.WordBoxBuilder()
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_word(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("words"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with open(os.path.join(tmpdir, "output.hocr"), "w") as fh:
fh.write("")
result = tesseract.image_to_string(self.image,
builder=self.builder)
for box in result:
self.assertIsInstance(box, builders.Box)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_word_error(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (1, "Error")
copen.return_value = StringIO(self._get_file_content("words"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, 1)
self.assertEqual(te.exception.message, "Error")
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_word_no_output(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "No file output")
copen.side_effect = FileNotFoundError(
errno.ENOENT,
"[Errno 2] No such file or directory: 'output'"
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, -1)
self.assertIn("Unable to find output file (tested",
te.exception.message)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
class TestTesseractLineBox(BaseTest):
@patch("pyocr.tesseract.get_version")
def setUp(self, get_version):
super().setUp()
get_version.return_value = (4, 0, 0)
self.image = Image.new(mode="RGB", size=(1, 1))
self.builder = builders.LineBoxBuilder()
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_line(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(
self._get_file_content("tesseract.lines")
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with open(os.path.join(tmpdir, "output.hocr"), "w") as fh:
fh.write("")
result = tesseract.image_to_string(self.image,
builder=self.builder)
for line in result:
self.assertIsInstance(line, builders.LineBox)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_line_error(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (1, "Error")
copen.return_value = StringIO(
self._get_file_content("tesseract.lines")
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, 1)
self.assertEqual(te.exception.message, "Error")
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_line_no_output(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "No file output")
copen.side_effect = FileNotFoundError(
errno.ENOENT,
"[Errno 2] No such file or directory: 'output'"
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, -1)
self.assertIn("Unable to find output file (tested",
te.exception.message)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
class TestTesseractDigitsLineBox(BaseTest):
@patch("pyocr.tesseract.get_version")
def setUp(self, get_version):
super().setUp()
get_version.return_value = (4, 0, 0)
self.image = Image.new(mode="RGB", size=(1, 1))
self.builder = builders.DigitLineBoxBuilder()
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_line(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "")
copen.return_value = StringIO(self._get_file_content("digits.lines"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with open(os.path.join(tmpdir, "output.hocr"), "w") as fh:
fh.write("")
result = tesseract.image_to_string(self.image,
builder=self.builder)
for line in result:
self.assertIsInstance(line, builders.LineBox)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_line_error(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (1, "Error")
copen.return_value = StringIO(self._get_file_content("digits.lines"))
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, 1)
self.assertEqual(te.exception.message, "Error")
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
@patch("tempfile.TemporaryDirectory")
@patch("codecs.open")
@patch("pyocr.tesseract.run_tesseract")
def test_line_no_output(self, run_tesseract, copen, temp_dir):
run_tesseract.return_value = (0, "No file output")
copen.side_effect = FileNotFoundError(
errno.ENOENT,
"[Errno 2] No such file or directory: 'output'"
)
with TemporaryDirectory(prefix="tess_") as tmpdir:
enter = MagicMock()
enter.__enter__.return_value = tmpdir
temp_dir.return_value = enter
with self.assertRaises(tesseract.TesseractError) as te:
tesseract.image_to_string(self.image, builder=self.builder)
self.assertEqual(te.exception.status, -1)
self.assertIn("Unable to find output file (tested",
te.exception.message)
run_tesseract.assert_called_once_with(
"input.bmp", "output", cwd=tmpdir, lang=None,
flags=self.builder.tesseract_flags,
configs=self.builder.tesseract_configs,
)
|