/usr/lib/python2.7/dist-packages/pyocr/tesseract.py is in python-pyocr 0.3.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #!/usr/bin/env python
'''
tesseract.py is a wrapper for google's Tesseract-OCR
( http://code.google.com/p/tesseract-ocr/ ).
USAGE:
> from PIL import Image
> from tesseract import image_to_string
> print(image_to_string(Image.open('test.png')))
> print(image_to_string(Image.open('test-european.jpg'), lang='fra'))
COPYRIGHT:
PyOCR is released under the GPL v3.
Copyright (c) Samuel Hoffstaetter, 2009
Copyright (c) Jerome Flesch, 2011-2012
https://github.com/jflesch/python-tesseract#readme
'''
import codecs
import os
import subprocess
import tempfile
from . import builders
from . import util
# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH, OR IS NAMED DIFFERENTLY
TESSERACT_CMD = 'tesseract'
TESSDATA_POSSIBLE_PATHS = [
"/usr/local/share/tessdata",
"/usr/share/tessdata",
"/usr/share/tesseract/tessdata",
"/usr/local/share/tesseract-ocr/tessdata",
"/usr/share/tesseract-ocr/tessdata",
"/app/vendor/tesseract-ocr/tessdata", # Heroku
"/opt/local/share/tessdata", # OSX MacPorts
]
TESSDATA_EXTENSION = ".traineddata"
__all__ = [
'CharBoxBuilder',
'DigitBuilder',
'can_detect_orientation',
'detect_orientation',
'get_available_builders',
'get_available_languages',
'get_name',
'get_version',
'image_to_string',
'is_available',
'TesseractError',
]
class CharBoxBuilder(object):
"""
If passed to image_to_string(), image_to_string() will return an array of
Box. Each box correspond to a character recognized in the image.
"""
file_extensions = ["box"]
tesseract_configs = ['batch.nochop', 'makebox']
def __init__(self):
pass
@staticmethod
def read_file(file_descriptor):
"""
Extract of set of Box from the lines of 'file_descriptor'
Return:
An array of Box.
"""
boxes = [] # note that the order of the boxes may matter to the caller
for line in file_descriptor.readlines():
line = line.strip()
if line == "":
continue
elements = line.split(" ")
if len(elements) < 6:
continue
position = ((int(elements[1]), int(elements[2])),
(int(elements[3]), int(elements[4])))
box = builders.Box(elements[0], position)
boxes.append(box)
return boxes
@staticmethod
def write_file(file_descriptor, boxes):
"""
Write boxes in a box file. Output is in a the same format than
tesseract's one.
Warning:
The file_descriptor must support UTF-8 ! (see module 'codecs')
"""
for box in boxes:
file_descriptor.write(box.get_unicode_string() + " 0\n")
@staticmethod
def __str__():
return "Character boxes"
class DigitBuilder(builders.TextBuilder):
"""
If passed to image_to_string(), image_to_string() will return a string with
only digits. Characters recognition will consider text as if it will only
composed by digits.
"""
@staticmethod
def __str__():
return "Digits only"
def __init__(self, tesseract_layout=3):
super(DigitBuilder, self).__init__(tesseract_layout)
self.tesseract_configs.append("digits")
def can_detect_orientation():
version = get_version()
return (
version[0] > 3
or (version[0] == 3 and version[1] >= 3)
)
def detect_orientation(image, lang=None):
"""
Arguments:
image --- Pillow image to analyze
lang --- lang to specify to tesseract
Returns:
{
'angle': 90,
'confidence': 23.73,
}
Raises:
TesseractError --- if no script detected on the image
"""
command = [TESSERACT_CMD, 'stdin', 'stdout', "-psm", "0"]
if lang is not None:
command += ['-l', lang]
image = image.convert("RGB")
proc = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
image.save(proc.stdin, format='png')
proc.stdin.close()
output = proc.stdout.read()
proc.wait()
try:
output = output.decode("utf-8")
output = output.strip()
output = output.split("\n")
output = [line.split(": ") for line in output]
output = {x: y for (x, y) in output}
angle = int(output['Orientation in degrees'])
# Tesseract reports the angle in the opposite direction the one we want
angle = (360 - angle) % 360
return {
'angle': angle,
'confidence': float(output['Orientation confidence']),
}
except:
raise TesseractError(-1, "No script found in image")
def get_name():
return "Tesseract"
def get_available_builders():
return [
builders.TextBuilder,
builders.WordBoxBuilder,
CharBoxBuilder,
]
def run_tesseract(input_filename, output_filename_base, lang=None,
configs=None):
'''
Runs Tesseract:
`TESSERACT_CMD` \
`input_filename` \
`output_filename_base` \
[-l `lang`] \
[`configs`]
Arguments:
input_filename --- image to read
output_filename_base --- file name in which must be stored the result
(without the extension)
lang --- Tesseract language to use (if None, none will be specified)
config --- List of Tesseract configs to use (if None, none will be
specified)
Returns:
Returns (the exit status of Tesseract, Tesseract's output)
'''
command = [TESSERACT_CMD, input_filename, output_filename_base]
if lang is not None:
command += ['-l', lang]
if configs is not None:
command += configs
proc = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
# Beware that in some cases, tesseract may print more on stderr than
# allowed by the buffer of subprocess.Popen.stderr. So we must read stderr
# asap or Tesseract will remain stuck when trying to write again on stderr.
# In the end, we just have to make sure that proc.stderr.read() is called
# before proc.wait()
errors = proc.stdout.read()
return (proc.wait(), errors)
def cleanup(filename):
''' Tries to remove the given filename. Ignores non-existent files '''
try:
os.remove(filename)
except OSError:
pass
def temp_file(suffix):
''' Returns a temporary file '''
return tempfile.NamedTemporaryFile(prefix='tess_', suffix=suffix)
class TesseractError(Exception):
"""
Exception raised when Tesseract fails.
"""
def __init__(self, status, message):
Exception.__init__(self, message)
self.status = status
self.message = message
self.args = (status, message)
def image_to_string(image, lang=None, builder=None):
'''
Runs tesseract on the specified image. First, the image is written to disk,
and then the tesseract command is run on the image. Tesseract's result is
read, and the temporary files are erased.
Arguments:
image --- image to OCR
lang --- tesseract language to use
builder --- builder used to configure Tesseract and read its result.
The builder is used to specify the type of output expected.
Possible builders are TextBuilder or CharBoxBuilder. If builder ==
None, the builder used will be TextBuilder.
Returns:
Depends of the specified builder. By default, it will return a simple
string.
'''
if builder is None:
builder = builders.TextBuilder()
with temp_file(".bmp") as input_file:
with temp_file('') as output_file:
output_file_name_base = output_file.name
image = image.convert("RGB")
image.save(input_file.name)
(status, errors) = run_tesseract(input_file.name,
output_file_name_base,
lang=lang,
configs=builder.tesseract_configs)
if status:
raise TesseractError(status, errors)
output_file_name = "ERROR"
for file_extension in builder.file_extensions:
output_file_name = ('%s.%s' % (output_file_name_base,
file_extension))
if not os.access(output_file_name, os.F_OK):
continue
try:
with codecs.open(output_file_name, 'r', encoding='utf-8',
errors='replace') as file_desc:
results = builder.read_file(file_desc)
return results
finally:
cleanup(output_file_name)
break
raise TesseractError(-1, "Unable to find output file"
" last name tried: %s" % output_file_name)
def is_available():
return util.is_on_path(TESSERACT_CMD)
def get_available_languages():
"""
Returns the list of languages that Tesseract knows how to handle.
Returns:
An array of strings. Note that most languages name conform to ISO 639
terminology, but not all. Most of the time, truncating the language
name name returned by this function to 3 letters should do the trick.
"""
langs = []
for dirpath in TESSDATA_POSSIBLE_PATHS:
if not os.access(dirpath, os.R_OK):
continue
for filename in os.listdir(dirpath):
if filename.lower().endswith(TESSDATA_EXTENSION):
lang = filename[:(-1 * len(TESSDATA_EXTENSION))]
langs.append(lang)
return langs
def get_version():
"""
Returns Tesseract version.
Returns:
A tuple corresponding to the version (for instance, (3, 0, 1) for 3.01)
Exception:
TesseractError --- Unable to run tesseract or to parse the version
"""
command = [TESSERACT_CMD, "-v"]
proc = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
ver_string = proc.stdout.read()
if hasattr(ver_string, 'decode'):
ver_string = ver_string.decode('utf-8')
ret = proc.wait()
if ret not in (0, 1):
raise TesseractError(ret, ver_string)
try:
els = ver_string.split(" ")[1].split(".")
els = [int(x) for x in els]
major = els[0]
minor = els[1]
upd = 0
if len(els) >= 3:
upd = els[2]
return (major, minor, upd)
except IndexError:
raise TesseractError(
ret, ("Unable to parse Tesseract version (spliting failed): [%s]"
% (ver_string)))
except ValueError:
raise TesseractError(
ret, ("Unable to parse Tesseract version (not a number): [%s]"
% (ver_string)))
|