/usr/lib/python3/dist-packages/pyocr/builders.py is in python3-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 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 | """
Builders: Each builder specifies the expected output format
raw text : TextBuilder
words + boxes : WordBoxBuilder
lines + words + boxes : LineBoxBuilder
"""
try:
from HTMLParser import HTMLParser
except ImportError:
from html.parser import HTMLParser
import xml.dom.minidom
from .util import to_unicode
__all__ = [
'Box',
'TextBuilder',
'WordBoxBuilder',
'LineBoxBuilder',
]
_XHTML_HEADER = to_unicode("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<head>
\t<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
""")
class Box(object):
"""
Boxes are rectangles around each individual element recognized in the
image. Elements are either char or word depending of the builder that
was used.
"""
def __init__(self, content, position):
"""
Arguments:
content --- a single string
position --- the position of the box on the image. Given as a
tuple of tuple:
((width_pt_x, height_pt_x), (width_pt_y, height_pt_y))
"""
if hasattr(content, 'decode'):
content = to_unicode("%s") % content
self.content = content
self.position = position
def get_unicode_string(self):
"""
Return the string corresponding to the box, in unicode (utf8).
This string can be stored in a file as-is (see write_box_file())
and reread using read_box_file().
"""
return to_unicode("%s %d %d %d %d") % (
self.content,
self.position[0][0],
self.position[0][1],
self.position[1][0],
self.position[1][1],
)
def get_xml_tag(self, parent_doc):
span_tag = parent_doc.createElement("span")
span_tag.setAttribute("class", "ocrx_word")
span_tag.setAttribute("title", ("bbox %d %d %d %d" % (
(self.position[0][0], self.position[0][1],
self.position[1][0], self.position[1][1]))))
txt = xml.dom.minidom.Text()
txt.data = self.content.encode('utf-8')
span_tag.appendChild(txt)
return span_tag
def __str__(self):
return self.get_unicode_string().encode('utf-8')
def __box_cmp(self, other):
"""
Comparison function.
"""
if other is None:
return -1
for (x, y) in ((self.position[0][1], other.position[0][1]),
(self.position[1][1], other.position[1][1]),
(self.position[0][0], other.position[0][0]),
(self.position[1][0], other.position[1][0])):
if x < y:
return -1
elif x > y:
return 1
return 0
def __lt__(self, other):
return self.__box_cmp(other) < 0
def __gt__(self, other):
return self.__box_cmp(other) > 0
def __eq__(self, other):
return self.__box_cmp(other) == 0
def __le__(self, other):
return self.__box_cmp(other) <= 0
def __ge__(self, other):
return self.__box_cmp(other) >= 0
def __ne__(self, other):
return self.__box_cmp(other) != 0
def __hash__(self):
position_hash = 0
position_hash += ((self.position[0][0] & 0xFF) << 0)
position_hash += ((self.position[0][1] & 0xFF) << 8)
position_hash += ((self.position[1][0] & 0xFF) << 16)
position_hash += ((self.position[1][1] & 0xFF) << 24)
return (position_hash ^ hash(self.content) ^ hash(self.content))
class LineBox(object):
"""
Boxes are rectangles around each individual element recognized in the
image. LineBox are boxes around lines. LineBox contains Box.
"""
def __init__(self, word_boxes, position):
"""
Arguments:
word_boxes --- a single string
position --- the position of the box on the image. Given as a
tuple of tuple:
((width_pt_x, height_pt_x), (width_pt_y, height_pt_y))
"""
self.word_boxes = word_boxes
self.position = position
def get_unicode_string(self):
"""
Return the string corresponding to the box, in unicode (utf8).
This string can be stored in a file as-is (see write_box_file())
and reread using read_box_file().
"""
txt = to_unicode("[\n")
for box in self.word_boxes:
txt += to_unicode(" %s\n") % box.get_unicode_string()
return to_unicode("%s] %d %d %d %d") % (
txt,
self.position[0][0],
self.position[0][1],
self.position[1][0],
self.position[1][1],
)
def __get_content(self):
txt = to_unicode("")
for box in self.word_boxes:
txt += box.content + to_unicode(" ")
txt = txt.strip()
return txt
content = property(__get_content)
def get_xml_tag(self, parent_doc):
span_tag = parent_doc.createElement("span")
span_tag.setAttribute("class", "ocr_line")
span_tag.setAttribute("title", ("bbox %d %d %d %d" % (
(self.position[0][0], self.position[0][1],
self.position[1][0], self.position[1][1]))))
for box in self.word_boxes:
space = xml.dom.minidom.Text()
space.data = " "
span_tag.appendChild(space)
box_xml = box.get_xml_tag(parent_doc)
span_tag.appendChild(box_xml)
return span_tag
def __str__(self):
return self.get_unicode_string().encode('utf-8')
def __box_cmp(self, other):
"""
Comparison function.
"""
if other is None:
return -1
for (x, y) in ((self.position[0][1], other.position[0][1]),
(self.position[1][1], other.position[1][1]),
(self.position[0][0], other.position[0][0]),
(self.position[1][0], other.position[1][0])):
if (x < y):
return -1
elif (x > y):
return 1
return 0
def __lt__(self, other):
return self.__box_cmp(other) < 0
def __gt__(self, other):
return self.__box_cmp(other) > 0
def __eq__(self, other):
return self.__box_cmp(other) == 0
def __le__(self, other):
return self.__box_cmp(other) <= 0
def __ge__(self, other):
return self.__box_cmp(other) >= 0
def __ne__(self, other):
return self.__box_cmp(other) != 0
def __hash__(self):
content = self.content
position_hash = 0
position_hash += ((self.position[0][0] & 0xFF) << 0)
position_hash += ((self.position[0][1] & 0xFF) << 8)
position_hash += ((self.position[1][0] & 0xFF) << 16)
position_hash += ((self.position[1][1] & 0xFF) << 24)
return (position_hash ^ hash(content) ^ hash(content))
class TextBuilder(object):
"""
If passed to image_to_string(), image_to_string() will return a simple
string. This string will be the output of the OCR tool, as-is. In other
words, the raw text as produced by the tool.
Warning:
The returned string is encoded in UTF-8
"""
file_extensions = ["txt"]
tesseract_configs = []
cuneiform_args = ["-f", "text"]
def __init__(self, tesseract_layout=3):
self.tesseract_configs = ["-psm", str(tesseract_layout)]
pass
@staticmethod
def read_file(file_descriptor):
"""
Read a file and extract the content as a string
"""
return file_descriptor.read().strip()
@staticmethod
def write_file(file_descriptor, text):
"""
Write a string in a file
"""
file_descriptor.write(text)
@staticmethod
def __str__():
return "Raw text"
class _WordHTMLParser(HTMLParser):
"""
Tesseract style: Tesseract provides handy but non-standard hOCR tags:
ocrx_word
"""
def __init__(self):
HTMLParser.__init__(self)
self.__tag_types = []
self.__current_box_position = None
self.__current_box_text = None
self.boxes = []
self.__current_line_position = None
self.__current_line_content = []
self.lines = []
@staticmethod
def __parse_position(title):
for piece in title.split("; "):
piece = piece.strip()
if not piece.startswith("bbox"):
continue
piece = piece.split(" ")
position = ((int(piece[1]), int(piece[2])),
(int(piece[3]), int(piece[4])))
return position
raise Exception("Invalid hocr position: %s" % title)
def handle_starttag(self, tag, attrs):
if (tag != "span"):
return
position = None
tag_type = None
for attr in attrs:
if attr[0] == 'class':
tag_type = attr[1]
if attr[0] == 'title':
position = attr[1]
if position is None or tag_type is None:
return
if tag_type == 'ocr_word' or tag_type == 'ocrx_word':
try:
position = self.__parse_position(position)
self.__current_box_position = position
except Exception:
# invalid position --> old format --> we ignore this tag
self.__tag_types.append("ignore")
return
self.__current_box_text = to_unicode("")
elif tag_type == 'ocr_line':
self.__current_line_position = self.__parse_position(position)
self.__current_line_content = []
self.__tag_types.append(tag_type)
def handle_data(self, data):
if self.__current_box_text is None:
return
data = to_unicode("%s") % data
self.__current_box_text += data
def handle_endtag(self, tag):
if tag != 'span':
return
tag_type = self.__tag_types.pop()
if tag_type == 'ocr_word' or tag_type == 'ocrx_word':
if self.__current_box_text is None:
return
box_position = self.__current_box_position
box = Box(self.__current_box_text, box_position)
self.boxes.append(box)
self.__current_line_content.append(box)
self.__current_box_text = None
return
elif tag_type == 'ocr_line':
line = LineBox(self.__current_line_content,
self.__current_line_position)
self.lines.append(line)
self.__current_line_content = []
return
@staticmethod
def __str__():
return "WordHTMLParser"
class _LineHTMLParser(HTMLParser):
"""
Cuneiform style: Cuneiform provides the OCR line by line, and for each
line, the position of all its characters.
Spaces have "-1 -1 -1 -1" for position".
"""
def __init__(self):
HTMLParser.__init__(self)
self.boxes = []
self.__line_text = None
self.__char_positions = None
def handle_starttag(self, tag, attrs):
TAG_TYPE_CONTENT = 0
TAG_TYPE_POSITIONS = 1
if (tag != "span"):
return
tag_type = -1
for attr in attrs:
if attr[0] == 'class':
if attr[1] == 'ocr_line':
tag_type = TAG_TYPE_CONTENT
elif attr[1] == 'ocr_cinfo':
tag_type = TAG_TYPE_POSITIONS
if tag_type == TAG_TYPE_CONTENT:
self.__line_text = to_unicode("")
self.__char_positions = []
return
elif tag_type == TAG_TYPE_POSITIONS:
for attr in attrs:
if attr[0] == 'title':
self.__char_positions = attr[1].split(" ")
# strip x_bboxes
self.__char_positions = self.__char_positions[1:]
if self.__char_positions[-1] == "":
self.__char_positions[:-1]
try:
while True:
self.__char_positions.remove("-1")
except ValueError:
pass
def handle_data(self, data):
if self.__line_text is None:
return
self.__line_text += data
def handle_endtag(self, tag):
if self.__line_text is None or self.__char_positions == []:
return
words = self.__line_text.split(" ")
for word in words:
if word == "":
continue
positions = self.__char_positions[0:4 * len(word)]
self.__char_positions = self.__char_positions[4 * len(word):]
left_pos = min([int(positions[x])
for x in range(0, 4 * len(word), 4)])
top_pos = min([int(positions[x])
for x in range(1, 4 * len(word), 4)])
right_pos = max([int(positions[x])
for x in range(2, 4 * len(word), 4)])
bottom_pos = max([int(positions[x])
for x in range(3, 4 * len(word), 4)])
box_pos = ((left_pos, top_pos), (right_pos, bottom_pos))
box = Box(word, box_pos)
self.boxes.append(box)
self.__line_text = None
@staticmethod
def __str__():
return "LineHTMLParser"
class WordBoxBuilder(object):
"""
If passed to image_to_string(), image_to_string() will return an array of
Box. Each box contains a word recognized in the image.
"""
file_extensions = ["html", "hocr"]
tesseract_configs = ['hocr']
cuneiform_args = ["-f", "hocr"]
def __init__(self):
pass
def read_file(self, file_descriptor):
"""
Extract of set of Box from the lines of 'file_descriptor'
Return:
An array of Box.
"""
parsers = [_WordHTMLParser(), _LineHTMLParser()]
html_str = file_descriptor.read()
for p in parsers:
p.feed(html_str)
if len(p.boxes) > 0:
return p.boxes
return []
@staticmethod
def write_file(file_descriptor, boxes):
"""
Write boxes in a box file. Output is a *very* *simplified* version
of hOCR.
Warning:
The file_descriptor must support UTF-8 ! (see module 'codecs')
"""
global _XHTML_HEADER
impl = xml.dom.minidom.getDOMImplementation()
newdoc = impl.createDocument(None, "root", None)
file_descriptor.write(_XHTML_HEADER)
file_descriptor.write(to_unicode("<body>\n"))
for box in boxes:
xml_str = to_unicode("%s") % box.get_xml_tag(newdoc).toxml()
file_descriptor.write(xml_str + to_unicode("<br/>\n"))
file_descriptor.write(to_unicode("</body>\n"))
@staticmethod
def __str__():
return "Word boxes"
class LineBoxBuilder(object):
"""
If passed to image_to_string(), image_to_string() will return an array of
LineBox. Each box contains a word recognized in the image.
"""
file_extensions = ["html", "hocr"]
tesseract_configs = ['hocr']
cuneiform_args = ["-f", "hocr"]
def __init__(self):
pass
def read_file(self, file_descriptor):
"""
Extract of set of Box from the lines of 'file_descriptor'
Return:
An array of LineBox.
"""
parsers = [
(_WordHTMLParser(), lambda parser: parser.lines),
(_LineHTMLParser(), lambda parser: [LineBox([box], box.position)
for box in parser.boxes]),
]
html_str = file_descriptor.read()
for (parser, convertion) in parsers:
parser.feed(html_str)
if len(parser.boxes) > 0:
return convertion(parser)
return []
@staticmethod
def write_file(file_descriptor, boxes):
"""
Write boxes in a box file. Output is a *very* *simplified* version
of hOCR.
Warning:
The file_descriptor must support UTF-8 ! (see module 'codecs')
"""
global _XHTML_HEADER
impl = xml.dom.minidom.getDOMImplementation()
newdoc = impl.createDocument(None, "root", None)
file_descriptor.write(_XHTML_HEADER)
file_descriptor.write(to_unicode("<body>\n"))
for box in boxes:
xml_str = box.get_xml_tag(newdoc).toxml()
if hasattr(xml_str, 'decode'):
xml_str = xml_str.decode('utf-8')
file_descriptor.write(xml_str + to_unicode("<br/>\n"))
file_descriptor.write(to_unicode("</body>\n"))
@staticmethod
def __str__():
return "Line boxes"
|