hocrTransform: code cleanup

This commit is contained in:
fritz-hh
2013-04-09 21:35:22 +02:00
parent 4e4b5ddc58
commit accc082b91
+43 -48
View File
@@ -4,7 +4,7 @@ from reportlab.lib.units import inch
from lxml import etree as ElementTree
import Image, re, sys
class HocrConverter():
class hocrTransform():
"""
A class for converting documents to/from the hOCR format.
For details of the hOCR format, see:
@@ -13,16 +13,20 @@ class HocrConverter():
http://code.google.com/p/hocr-tools/
Basic usage:
Create a PDF from an hOCR file and an image:
hocr = HocrConverter("path/to/hOCR/file")
hocr = hocrTransform("path/to/hOCR/file")
hocr.to_pdf("path/to/image/file", "path/to/output/file")
"""
def __init__(self, hocrFileName = None):
def __init__(self, hocrFileName = None, dpi=300):
self.hocr = None
self.dpi = dpi
self.xmlns = ''
self.boxPattern = re.compile('bbox((\s+\d+){4})')
if hocrFileName is not None:
self.parse_hocr(hocrFileName)
else:
print "No hocr file provided. exiting"
exit
def __str__(self):
"""
Return the textual content of the HTML body
@@ -74,54 +78,42 @@ class HocrConverter():
self.xmlns = matches.group(1)
else:
self.xmlns = ''
def pxl2pt(self, pxl):
"""
Returns the length in pt given length in pxl
"""
return float(pxl)/self.dpi*inch
def to_pdf(self, imageFileName, outFileName, fontname="Courier"):
"""
Creates a PDF file with an image superimposed on top of the text.
Text is positioned according to the bounding box of the lines in
the hOCR file.
The image need not be identical to the image used to create the hOCR file.
It can be scaled, have a lower resolution, different color mode, etc.
It can have a lower resolution, different color mode, etc.
"""
if self.hocr is None:
print "No hocr file provided. exiting"
exit
im = Image.open(imageFileName)
if 'dpi' in im.info:
width = float(im.size[0])/im.info['dpi'][0]
height = float(im.size[1])/im.info['dpi'][1]
else:
# we have to make a reasonable guess
# set to None for now and try again using info from hOCR file
width = height = None
# get dimensions of the OCR, which may not match the image
ocr_dpi = (300, 300) # a default, in case we can't find it
# get dimension of the OCRed image
for div in self.hocr.findall(".//%sdiv[@class='ocr_page']"%(self.xmlns)):
coords = self.element_coordinates(div)
ocrwidth = coords[2]-coords[0]
ocrheight = coords[3]-coords[1]
if width is None:
# no dpi info with the image
# assume OCR was done at 300 dpi
width = ocrwidth/300
height = ocrheight/300
ocr_dpi = (ocrwidth/width, ocrheight/height)
width = self.pxl2pt(coords[2]-coords[0])
height = self.pxl2pt(coords[3]-coords[1])
break # there shouldn't be more than one, and if there is, we don't want it
if width is None:
# no dpi info within the image, and no help from the hOCR file either
# this will probably end up looking awful, so issue a warning
print "Warning: DPI unavailable for image %s. Assuming 300 DPI."%(imageFileName)
width = float(im.size[0])/300
height = float(im.size[1])/300
# no width and heigh definition in the ocr_image element of the hocr file
# assuming page size is A4
print "page width and height not available in %s. Assuming A4."%(imageFileName)
width = 21*2.54*inch
height = 29.6*2.54*inch
# create the PDF file
pdf = Canvas(outFileName, pagesize=(width*inch, height*inch), pageCompression=1) # page size in points (1/72 in.)
pdf = Canvas(outFileName, pagesize=(width, height), pageCompression=1) # page size in points (1/72 in.)
# put the image on the page, scaled to fill the page
#pdf.drawInlineImage(im, 0, 0, width=width*inch, height=height*inch)
#pdf.drawInlineImage(im, 0, 0, width=width, height=height)
# check if element with class 'ocrx_word' are available
# otherwise use 'ocr_line' as fallback
@@ -129,7 +121,7 @@ class HocrConverter():
if self.hocr.find(".//%sspan[@class='ocrx_word']" %(self.xmlns)) is not None:
elemclass="ocrx_word"
# itterate all text elements
for elem in self.hocr.findall(".//%sspan[@class='%s']" % (self.xmlns, elemclass)):
elemtxt=self._get_element_text(elem).rstrip()
@@ -137,23 +129,26 @@ class HocrConverter():
continue
coords = self.element_coordinates(elem)
x1=self.pxl2pt(coords[0])
y1=self.pxl2pt(coords[1])
x2=self.pxl2pt(coords[2])
y2=self.pxl2pt(coords[3])
# compute font size according to bbox coordinates
fontsize=(coords[3]-coords[1])/(ocr_dpi[1]*(0.35146/25.4))
fontsize=self.pxl2pt(coords[3]-coords[1])
# draw the bbox border
#pdf.rect((float(coords[0])/ocr_dpi[0])*inch, (height*inch)-(float(coords[3])/ocr_dpi[1])*inch,(float(coords[2]-coords[0])/ocr_dpi[0])*inch, float(coords[3]-coords[1])/ocr_dpi[1]*inch, fill=0)
pdf.rect(x1, height-y2, x2-x1, y2-y1, fill=0)
text = pdf.beginText()
text.setFont(fontname, fontsize)
#text.setTextRenderMode(3) # invisible
# set cursor to bottom left corner of bbox (adjust for dpi)
text.setTextOrigin((float(coords[0])/ocr_dpi[0])*inch, (height*inch)-(float(coords[3])/ocr_dpi[1])*inch)
text.setTextOrigin(x1, height-y2)
# scale the width of the text to fill the width of the bbox
text.setHorizScale((((float(coords[2])/ocr_dpi[0]*inch)-(float(coords[0])/ocr_dpi[0]*inch))/pdf.stringWidth(elemtxt, fontname, fontsize))*100)
text.setHorizScale(100*(x2-x1)/pdf.stringWidth(elemtxt, fontname, fontsize))
# write the text to the page
text.textLine(elemtxt)
@@ -165,7 +160,7 @@ class HocrConverter():
if __name__ == "__main__":
if len(sys.argv) < 4:
print 'Usage: python HocrConverter.py inputHocrFile inputImageFile outputPdfFile'
print 'Usage: python hocrTransform.py inputHocrFile inputImageFile outputPdfFile'
sys.exit(1)
hocr = HocrConverter(sys.argv[1])
hocr = hocrTransform(sys.argv[1])
hocr.to_pdf(sys.argv[2], sys.argv[3])