Handprint

The Handwritten Page Recognition Test is a command-line program that invokes HTR (handwritten text recognition) services on images of document pages. It can produce annotated images showing the results, compare the recognized text to expected text, save the HTR service results as JSON and text files, and more.

☞ Introduction

Handprint (Handwritten Page Recognition Test) is a tool for comparing alternative services for offline handwritten text recognition (HTR). It was developed for use with documents from the Caltech Archives, but it is completely independent and can be applied to any images of text documents.

Handprint can generate images with recognized text overlaid over them to visualize the results. The image at right shows an example. Among other features, the software can also display bounding boxes, threshold results by confidence values, compare full-text results to expected/ground-truth results, and output the raw results from an HTR service as JSON and text files. It can work with individual images, directories of images, and URLs pointing to images on remote servers. Finally, Handprint can use multiple processor threads for parallel execution.

Services supported include Google's Google Cloud Vision API, Microsoft's Azure Computer Vision API, and Amazon's Textract and Rekognition. The framework for connecting to services could be expanded to support others as well (and contributions are welcome!).

✎ Installation and configuration

The instructions below assume you have a Python interpreter version 3.8 or higher installed on your computer; if that's not the case, please first install Python and familiarize yourself with running Python programs on your system. If you are unsure of which version of Python you have, you can find out by running the following command in a terminal and inspecting the results:

# Note: on Windows, you may have to use "python" instead of "python3"
python3 --version

Note for Mac users: if you are using macOS Catalina (10.15) or later and have never run python3, then the first time you do, macOS will ask you if you want to install the macOS command-line developer tools. Go ahead and do so, as this is the easiest way to get a recent-enough Python 3 on those systems.

Handprint includes several adapters for working with cloud-based HTR services from Amazon, Google, and Microsoft, but does not include credentials for using the services. To be able to use Handprint, you must both install a copy of Handprint on your computer and supply your copy with credentials for accessing the cloud services you want to use.

⓵   Install Handprint on your computer

MacOS systems

The latest Handprint release provides a standalone runnable application for macOS that only needs a Python 3 interpreter on your computer – you do not need to run pip install as described below. Visit the Handprint releases page and look for the ZIP files with names such as (e.g.) handprint1.5.1-macos-python3.8.zip. Download the one matching your version of Python, unzip the file, and the result will be a folder containing handprint, a runnable application.

Windows and Linux (and alternative approach for macOS)

On Windows and Linux systems (and if you prefer this installation approach on macOS too), you should be able to install Handprint with pip. If you don't have the pip package or are uncertain if you do, first run the following command in a terminal command line interpreter:

sudo python3 -m ensurepip

Then, to install or upgrade Handprint from the Python package repository, run the following command:

python3 -m pip install handprint --upgrade

As an alternative to getting it from PyPI, you can instruct pip to install or upgrade Handprint directly from the GitHub repository:

python3 -m pip install git+https://github.com/caltechlibrary/handprint.git --upgrade

⓶   Add cloud service credentials

A one-time configuration step is needed for each cloud-based HTR service after you install Handprint on a computer. This step supplies Handprint with credentials to access the services. In each case, the same command format is used:

handprint -a SERVICENAME CREDENTIALSFILE.json

SERVICENAME must be one of the service names printed by running handprint -l, and CREDENTIALSFILE.json must have one of the formats discussed below. When you run this command, Handprint copies CREDENTIALSFILE.json to a private location, and thereafter uses the credentials to access SERVICENAME. (The private location is different on different systems; for example, on macOS it is ~/Library/Application Support/Handprint/.) Examples are given below.

Microsoft

Microsoft's approach to credentials in Azure involves the use of subscription keys. The format of the credentials file for Handprint needs to contain two fields:

{
 "subscription_key": "YOURKEYHERE",
 "endpoint": "https://ENDPOINT"
}

The value "YOURKEYHERE" will be a string such as "18de248475134eb49ae4a4e94b93461c", and it will be associated with an endpoint URI such as "https://westus.api.cognitive.microsoft.com". To obtain a key and the corresponding endpoint URI, visit https://portal.azure.com and sign in using your account login. (Note: you will need to turn off browser security plugins such as Ad Block and uMatrix if you have them, or else the site will not work.) Once you are authenticated to the Azure portal, you can create credentials for using Azure's machine-learning services. Some notes all about this can be found in the Handprint project Wiki pages on GitHub.

Once you have obtained both a key and an endpoint URI, use a text editor to create a JSON file in the simple format shown above, save that file somewhere on your computer (for the sake of this example, assume it is myazurecredentials.json), and use the command discussed above to make Handprint copy the credentials file:

handprint -a microsoft myazurecredentials.json

Google

Credentials for using a Google service account need to be stored in a JSON file that contains many fields. The overall format looks like this:

{
  "type": "service_account",
  "project_id": "theid",
  "private_key_id": "thekey",
  "private_key": "-----BEGIN PRIVATE KEY-----anotherkey-----END PRIVATE KEY-----\n",
  "client_email": "emailaddress",
  "client_id": "id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "someurl"
}

Getting one of these is summarized in the Google Cloud docs for Creating a service account, but more explicit instructions can be found in the Handprint project Wiki pages on GitHub. Once you have downloaded a Google credentials file from Google, save the file somewhere on your computer (for the sake of this example, assume it is mygooglecredentials.json), and use the command discussed above to make Handprint copy the credentials file:

handprint -a google mygooglecredentials.json

Amazon

Amazon credentials for AWS take the form of two alphanumeric strings: a key id string and a secret access key string. In addition, the service needs to be invoked with a region identifier. For the purposes of Handprint, these should be stored in a JSON file with the following format:

{
    "aws_access_key_id": "YOUR_KEY_ID_HERE",
    "aws_secret_access_key": "YOUR_ACCESS_KEY_HERE",
    "region_name": "YOUR_REGION_NAME_HERE"
}

Getting this information is, thankfully, a relatively simple process for Amazon's services. Instructions can be found in the Handprint project Wiki pages on GitHub. Once you have obtained the two alphanumeric keys and a region identifier string, use a text editor to create a JSON file in the simple format shown above, save that file somewhere on your computer (for the sake of this example, assume it is myamazoncredentials.json), and use two commands to make Handprint copy the credentials file for the two different Amazon services currently supported by Handprint:

handprint -a amazon-textract myamazoncredentials.json
handprint -a amazon-rekognition myamazoncredentials.json

▶︎ Usage

Handprint comes with a single command-line interface program called handprint. Here is a screen cast to give a sense for what it's like to run Handprint. Click on the following image:

Screencast of simple Handprint demo

The handprint command-line program should end up installed in a location where software is normally installed on your computer, if the installation steps described in the previous section proceed successfully. Running Handprint from a terminal shell then should be as simple as running any other shell command on your system:

handprint -h

If that fails for some reason, you should be able to run Handprint from anywhere using the normal approach for running Python modules:

python3 -m handprint -h

The -h option (/h on Windows) will make handprint display some help information and exit immediately. To make Handprint do more, you can supply other arguments that instruct Handprint to process image files (or alternatively, URLs pointing to image files at a network location) and run text recognition algorithms on them, as explained below.

Input files and URLs

After credentials are installed, running Handprint without the -a option will invoke one or more services on files, directories of files, or URLs pointing to files. Here is an example of running Handprint on a directory containing images:

handprint tests/data/caltech-archives/glaser/

Image paths or URLs can be supplied to Handprint in any of the following ways:

  • One or more directory paths or one or more image file paths on the local disk, which will be interpreted as images (either individually or in directories) to be processed
  • One or more URLs, which will be interpreted as network locations of image files to be processed
  • If given the -f option (/f on Windows), a file containing either image paths or image URLs to be processed

Handprint assumes a path is a URL if it meets the test of is_url(...) from the Python Validator Collection. For every input given as a URL, Handprint will first download the image found at the URL to a directory indicated by the option -o (/o on Windows), or the current directory if option -o is not used.

No matter whether files or URLs, each input item should be a single image of a document page in which text should be recognized. Handprint reads a number of common formats: JP2, JPEG, PDF, PNG, GIF, BMP, and TIFF. However, for simplicity and maximum compatibility with all cloud services, Handprint always converts all input files to PNG if they are not already in that format, no matter if a given service can accept other formats. Handprint also reduces the size of input images to the smallest size accepted by any of the services invoked if an image exceeds that size. (For example, when sending a file to services A and B at the same time, if service A accepts files up to 10 MB in size and service B accepts files up to 4 MB, Handprint will resize the file to 4 MB before sending it to both A and B, even if A could accept a higher-resolution image.) Finally, if the input contains more than one page (e.g., in a PDF file), Handprint will only use the first page of the input and ignore the remaining pages.

Be aware that downsizing images can change the text recognition results returned by some services compared to the results obtained using the original full-size input image. If your images are larger when converted to PNG than the smallest size accepted by one of the destination services (currently 4 MB, for Microsoft), then you may wish to compare the results of using multiple services at once versus one at a time (i.e., one destination at a time in separate invocations of Handprint).

Finally, note that providing URLs on the command line can be problematic due to how terminal shells interpret certain characters, and so when supplying URLs, it's usually better to store the URLs in a file in combination with the -f option (/f on Windows).

Selecting destination services

You can use the -l option (/l on Windows) to make it display a list of the services currently supported by Handprint:

# handprint -l
Known services: amazon-rekognition, amazon-textract, google, microsoft

By default, Handprint will send images to all of the known services, creating annotated images to represent the results of each individual service. To invoke only specific services, use the -s option (/s on Windows) followed by a service name or a list of names separated by commas (e.g., google,microsoft). For example, the following command will invoke Microsoft's text recognition service on a page from Clara Barton's unpublished draft book "The Life of My Childhood", available in Handprint's source directory:

handprint -s microsoft tests/data/public-domain/images/clara-barton-life-of-my-childhood-p90.jpg

Here is the result of that command:

Example of running Microsoft's service on a page from Clara Barton's unpublished draft book, The Life of My Childhood.

Visual display of recognition results

After gathering the results of each service for a given input, Handprint will create a single compound image consisting of the results for each service arranged in a N×N grid. This overview image is intended to make it easier to compare the results of multiple services against each other. The grid image will have the suffix .handprint-all.png. Here is a sample output image to illustrate:

Example annotated results output image

The 2×2 image above was produced by running the following command from the Handprint tests/data/caltech-archives/glaser directory:

handprint --text-size 20  "DAG_5_1_6 1952-1957 Notebook VI p2.jpg"

To move the position of the text annotations overlaid over the input image, you can use the option -m (or /m on Windows). This takes two numbers separated by a comma in the form x,y. Positive numbers move the text rightward and upward, respectively, relative to the default position. The default position of each text annotation in the annotated output is such that the left edge of the word starts at the location of the upper left corner of the bounding box returned by the service; this has the effect of putting the annotation near, but above, the location of the (actual) word in the input image by default. For example, if the word in the image is strawberry, the bounding box returned by the service will enclose strawberry, and the upper left corner of that bounding box will be somewhere above the letter s. Then, the default position of the text annotation will put the left edge of the word "strawberry" at that point above the letter s. Using the move-text option allows you to move the annotation if desired. A value such as 0,-5 will move it downward five pixels.

To change the color of the text annotations overlaid over the input image, you can use the option -x (or /x on Windows). You can use hex color codes such as "#ff0000" (make sure to enclose the value with quotes, or the shell will interpret the pound sign as a comment character), or X11/CSS4 color names with no spaces such as purple or darkgreen.

To change the size of the text annotations overlaid over the input image, you can use the option -z (or /z on Windows). The value is in units of points. The default size is 12.

Finally, the individual results, as well as individual annotated images corresponding to the results from each service, will not be retained unless the -e extended results option (/e on Windows) is invoked (described in more detail below). The production of the overview grid image can be skipped by using the -G option (/G on Windows).

Annotation types

Handprint produces copies of the input images overlaid with the recognition results received from the different services. By default, it shows only the recognized text. The option -d (/d on Windows) can be used to tell Handprint to display other results. The recognized values are as follows:

  • text: display the text recognized in the image (default)
  • bb: display all bounding boxes returned by the service
  • bb-word: display the bounding boxes for words (in red)
  • bb-line: display the bounding boxes for lines (in blue)
  • bb-para: display the bounding boxes for paragraphs (in green)

Separate multiple values with a comma. The option bb is a shorthand for the value bb-word,bb-line,bb-para. As an example, the following command will show both the recognized text and the bounding boxes around words:

handprint -d text,bb-word  -s google  tests/data/public-domain/images/H96566k.jpg

And here is the output from that command:

Example of bounding boxes

Note that as of June 2021, the main services (Amazon, Google, Microsoft) do not all provide the same bounding box information in their results. The following table summarizes what is available:

Service Word
bounding boxes
Line
bounding boxes
Paragraph
bounding boxes
Amazon Y Y -
Google Y - Y
Microsoft Y Y -

If a service does not provide a particular kind of bounding box, Handprint will not display that kind of
bounding box in the annotated output for that service.

Thresholding by confidence

All of the services return confidence scores for items recognized in the input. By default, Handprint will show all results no matter how low the confidence score. The option -n (/n on Windows) can be used to threshold the results based on the confidence value for each item (text or bounding boxes). The value provided as the argument to the option must be a floating point number between 0 and 1.0. For example, the following command will make Handprint only show text that is rated with least 99.5% confidence:

handprint -n 0.995  somefile.png

Note that the confidence values returned by the different services are not normalized against each other. What one service considers to be 80% confidence may not be what another service considers 80% confidence. Handprint performs the thresholding against the raw scores returned by each service individually.

Comparison to ground truth text

Handprint offers the ability to compare the output of HTR services to expected output (i.e., ground truth) using the option -c (or /c on Windows). This facility requires that the user provides text files that contain the expected text for each input image. The ground-truth text files must have the following characteristics:

  • The file containing the expected results should be named .gt.txt, with a base name identical to the image file. For example, an image file named somefile.jpg should have a corresponding text file somefile.gt.txt. (This is a convention used by some other tools such as ocropy.)
  • The ground-truth text file should be located in the same directory as the input image file.
  • The text should be line oriented, with each line representing a line of text in the image.
  • The text should be plain text only. No Unicode or binary encodings. (This limitation comes from the HTR services, which – as of this writing – return results in plain text format.)

Handprint will write the comparison results to a tab-delimited file named after the input image and service but with the extension .tsv. For example, for an input image somefile.jpg and results received from Google, the comparison results will be written to somefile.handprint-google.tsv. The use of a tab-delimited format rather than comma-delimited format avoids the need to quote commas and other characters in the text. The output file will have one row for each line of text in the input, plus an additional row at the end for total number of errors found. Each row will have the following columns:

  1. number of errors on that line of text (computed as Levenshtein distance),
  2. the character error rate (CER) for the line (see below)
  3. the expected text on that line
  4. the text received from the service for that line

The character error rate (CER) is computed as

100 × (i + s + d)/n

where i is the number of inserted characters, s the number of substituted characters, and d the number of deleted characters needed to transform the the text received into the expected text, and n is the number of characters in the expected text line. This approach to normalizing the CER value is conventional but note that it can lead to values greater than 100%.

By default, scoring is done by Handprint on an exact basis; character case is not changed, punctuation is not removed, and stop words are not removed. However, multiple contiguous spaces are converted to one space, and leading spaces are removed from text lines.

If given the option -r (/r on Windows), Handprint will relax the comparison algorithm further, as follows: it will convert all text to lower case, and it will ignore certain sentence punctuation characters, namely ,, ., :, and ;. The rationale for these particular choices comes from experience with actual texts and HTR services. For example, a difference sometimes seen between HTR services is how they handle seemingly large spaces between a word and a subsequent comma or period: sometimes the HTR service will add a space before the comma or period, but inspection of the input document will reveal sloppiness in the author's handwriting and neither the addition nor the omission of a space is provably right or wrong. To avoid biasing the results one way or another, it is better to omit the punctuation. On the other hand, this may not always be desirable, and thus needs to be a user-controlled option.

Handprint attempts to cope with possibly-missing text in the HTR results by matching up likely corresponding lines in the expected and received results. It does this by comparing each line of ground-truth text to each line of the HTR results using longest common subsequence similarity as implemented by the LCSSEQ function in the textdistance package. If the lines do not pass a threshold score, Handprint looks at subsequent lines of the HTR results and tries to reestablish correspondence to ground truth. If nothing else in the HTR results appear close enough to the expected ground-truth line, the line is assumed to be missing from the HTR results and scored appropriately.

The following is an example of a tab-separated file produced using -c. This example shows a case where two lines were missing entirely from the HTR results; for those lines, the number of errors equals the length of the ground-truth text lines and the CER is 100%.

Extended results

If the option -e (/e on Windows) is used, Handprint saves not only the overview image containing all the results, but also, individual annotated images for each service's results, the raw data (converted to a JSON file by Handprint), and the text extracted by the service. These additional outputs will be written in files named after the original files with the addition of a string that indicates the service used. For example, a file named somefile.jpg will produce

somefile.handprint-amazon-textract.png
somefile.handprint-amazon-textract.json
somefile.handprint-amazon-textract.txt
somefile.handprint-google.png
somefile.handprint-google.json
somefile.handprint-google.txt
...

A complication arises with using URLs in combination with the -e option: how should Handprint name the files that it writes? Some CMS systems store content using opaque schemes that provide no clear names in the URLs, making it impossible for a software tool such as Handprint to guess what file name would make sense to use for local storage. Worse, some systems create extremely long URLs, making it impractical to use the URL itself as the file name. For example, the following is a real URL pointing to an image in Caltech Archives:

https://hale.archives.caltech.edu/adore-djatoka//resolver?rft_id=https%3A%2F%2Fhale.archives.caltech.edu%2Fislandora%2Fobject%2Fhale%253A85240%2Fdatastream%2FJP2%2Fview%3Ftoken%3D7997253eb6195d89b2615e8fa60708a97204a4cdefe527a5ab593395ac7d4327&url_ver=Z39.88-2004&svc_id=info%3Alanl-repo%2Fsvc%2FgetRegion&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajpeg2000&svc.format=image%2Fjpeg&svc.level=4&svc.rotate=0

To deal with this situation, Handprint manufactures its own file names when a URL is encountered. The scheme is simple: by default, Handprint will use a base name of document-N, where N is an integer. The integers start from 1 for every run of Handprint, and the integers count the URLs found either on the command line or in the file indicated by the -f option. The image found at a given URL is stored in a file named document-N.E where E is the format extension (e.g., document-1.jpg, document-1.png, etc.). The URL itself is stored in another file named document-1.url. Thus, the files produced by Handprint will look like this when the -e option is used (assuming, for this example, that the files at the source URLs are in JPEG format):

document-1.jpg
document-1.url
document-1.handprint-google.png
document-1.handprint-google.json
document-1.handprint-google.txt
document-1.handprint-microsoft.png
document-1.handprint-microsoft.json
document-1.handprint-microsoft.txt
...
document-2.jpg
document-2.url
document-2.handprint-google.png
document-2.handprint-google.json
document-2.handprint-google.txt
document-2.handprint-microsoft.png
document-2.handprint-microsoft.json
document-2.handprint-microsoft.txt
...
document-3.jpg
document-3.url
document-3.handprint-google.png
document-3.handprint-google.json
document-3.handprint-google.txt
document-3.handprint-microsoft.png
document-3.handprint-microsoft.json
document-3.handprint-microsoft.txt
...

The base name document can be changed using the -b option (/b on Windows). For example, running Handprint with the option -b einstein will cause the outputs to be named einstein-1.jpg, einstein-1.url, etc.

Other options

The option -j (/j on Windows) tells Handprint to look for and reuse preexisting results for each input instead of contacting the services. This makes it look for JSON files produced in a previous run with the -e option,

somefile.handprint-amazon-rekognition.json
somefile.handprint-amazon-textract.json
somefile.handprint-google.json
somefile.handprint-microsoft.json

and use those instead of getting results from the services. This can be useful to save repeated invocations of the services if all you want is to draw the results differently or perform some testing/debugging on the same inputs.

Handprint will send files to the different services in parallel, using a number of process threads equal to 1/2 of the number of cores on the computer it is running on. (E.g., if your computer has 4 cores, it will by default use at most 2 threads.) The -t option (/t on Windows) can be used to change this number.

If given the -q option (/q on Windows), Handprint will not print its usual informational messages while it is working. It will only print messages for warnings or errors. By default messages printed by Handprint are also color-coded. If given the option -Z (/Z on Windows), Handprint will not color the text of messages it prints. (This latter option is useful when running Handprint within subshells inside other environments such as Emacs.)

If given the [email protected] argument (/@ on Windows), this program will output a detailed trace of what it is doing. The debug trace will be sent to the given destination, which can be - to indicate console output, or a file path to send the output to a file. On non-Windows platforms, Handprint will also install a signal handler that responds to signal SIGUSR1; if the signal is sent to the running process, it will drop Handprint into the pdb debugger. Note: It's best to use -t 1 when attempting to use a debugger because otherwise subthreads will continue running even if the main thread is interrupted.

If given the -V option (/V on Windows), this program will print the version and other information, and exit without doing anything else.

Command line options summary

The following table summarizes all the command line options available. (Note: on Windows computers, / must be used as the prefix character instead of the - dash character):

Short     Long form Meaning Default
-aA --add-credsA Add credentials for service A and exit
-bB --base-nameB Write outputs to files named B-n Use base names of image files
-C --no-color Don't color-code info messages Color-code terminal output
-c --compare Compare to ground truth; see -r too
-dD --displayD Display annotation types D Display text annotations
-e --extended Produce extended results Produce only summary image
-fF --from-fileF Read file names or URLs from file F Use args on the command line
-G --no-grid Don't create summary image Create an N×N grid image
-h --help Display help, then exit
-j --reuse-json Reuse prior JSON results if found Ignore any existing results
-l --list Display known services and exit
-mx,y --text-movex,y Move each text annotation by x,y 0,0
-nN --confidenceN Use confidence score threshold N 0
-oO --outputO Write all outputs to directory O Write to images' directories
-q --quiet Don't write messages while working Be chatty while working
-r --relaxed Use looser criteria for --compare
-sS --serviceS Use recognition service S; see -l Use all services
-tT --threadsT Use T number of threads Use (#cores)/2 threads
-V --version Write program version info and exit
-xX --text-colorX Use color X for text annotations Red
-zZ --text-sizeZ Use font size Z for text annotations Use font size 12
[email protected]OUT --debugOUT Write detailed execution info to OUT Normal mode

⚑   If URLs are given, then the outputs will be written by default to names of the form document-n, where n is an integer. Examples: document-1.jpg, document-1.handprint-google.txt, etc. This is because images located in network content management systems may not have any clear names in their URLs.

★   The possible values of D are: text, bb, bb-word, bb-line, bb-para. Multiple values must be separated with commas. The value bb is a shorthand for bb-word,bb-line,bb-para. The default is text.

⬥   To write to the console, use the character - as the value of OUT; otherwise, OUT must be the name of a file where the output should be written.

Return values

This program exits with a return code of 0 if no problems are encountered. It returns a nonzero value otherwise. The following table lists the possible return values:

Code Meaning
0 success – program completed normally
1 the user interrupted the program's execution
2 encountered a bad or missing value for an option
3 no network detected – cannot proceed
4 file error – encountered a problem with a file
5 server error – encountered a problem with a server
6 an exception or fatal error occurred

Additional notes

The debug logging functionality is implemented using Sidetrack and all calls to the debug code are conditionalized on the Python symbol __debug__. It is carefully written so that you can cause the calls to be optimized out completely if your run Python with optimization turned on (e.g., using the -O command-line option).

☹︎ Known issues and limitations

Here are some known limitations in the current version of Handprint:

  • If the input has multiple pages, only the first page/image is used; the rest (if any) are ignored.
  • The Amazon Rekognition API will return at most 50 words in an image.
  • The Microsoft Azure API will only detect a maximum of 300 lines of text per page.
  • Some services have different file size restrictions depending on the format of the file, but Handprint always uses the same limit for all files for a given service. This is a code simplification.

GitHub

https://github.com/caltechlibrary/handprint