Skip to main content

Putting Form Recognizer on test - Extract labels from flight tickets (Cognitive Services)

Have you ever need to extract content from a document or image? I’m not referring just plain text, but key-values like tuples (e.g. name: Tom, age: 18) without having to do any additional manual steps.

Form Recognizer
At this moment in time, we can find in private preview on Azure – Form Recognizer. It a service part of Cognitive Services that have an ML behind the scene, allowing us to analyse digital content and extract data that it is in key-value pairs or table data from forms.

Overview of the service
The service can automatically extract this information without requiring us to do labelling of data. We need to provide at least 5 samples that are used by Form Recognizer to train the model. Once we have the model trained, we can start to extract content from our digital library.
The API provided by the service can be used to get, delete or train a model and extract the keys and values. There is an SDK that is built on top of it for .NET, but for testing purpose, I used the API together with curl. The output is provided in JSON or XML, that should work in most of the situations.

There is a prebuild model for receipts that works fantastic. I invite you to give it a try to see how well works with any receipts. The custom models are trained by ourself by uploading at least 5 samples. They might not work so good as the prebuilt models, but an out of the box solutions it is pretty amazing. For now, we can’t define and label custom keys or push our trained model.
Form Recognizer can be used directly from Azure in a SaaS model or can be configured to run inside your on-premises as 2 Docker containers. By allowing us to run on the edge devices, Form Recognizer becomes a good candidate for a service that can be integrated into our pipelines inside banks or financial institutes.

If you want to see my slide deck related to Form Recognizer please check the next link - http://vunvulearadu.blogspot.com/2019/12/post-event-global-ai-bootcamp-cluj.html

Flight tickets – the real test
I decided to test Form Recognizer with a form that is not pre-build – flight tickets. The purpose was to see the number of labels that can be identified with success by the service when we are using 5 documents for training.
In general, when you need to train a model, you need hundreds of items. Using just 5 items sounds impressive and I wanted to see how it would behave. I upload 5 older plane tickets that I had from the past and also used another 3 to see how well the labelling is done.

The keys extract from the document are marked with RED and the values with BLACK. The line between them represents the mapping between key and value. The rendering was possible because each key and value retuned by Form Recognize contains the coordinates on the document.

For a plane ticket the model was able to:
  • 38 keys
  • 29 values
  • 29 mappings between keys and values
  • 9 keys without a value
  • 9 values that were marked as keys (the 9 keys from the previous point)
  • 5 labels that were missed (where the key was available, but not well aligned)

After reviewing the result and eliminating the results where the confidence level was under 1 we have the following output:
  • 29 keys
  • 28 values
  • 28 mappings between keys and values
  • 1 key without a value

As we can see from the above result, the confidence level is a good indicator that can help us to eliminate false-positive results. By reviewing the final result that was provided by the Form Recognizer, we could say that we can extract easilty necessary information from the flight ticket using Form Recognizer. 
The errors appear especially for labels without a key or when the value of the key is not in close proximity of the value.

Result review
I am satisfied with the result. There were some narrow cases where the labelling was wrong, but overall the result is excellent. I hope that in the future we will be able to do some model optimization that could improve our overall experience with the service.

Do you want to try by yourself?
Follow the steps specified on Azure - https://docs.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/curl-train-extract. The crunking of first 500 pages are free.
Below you can find the scripts that I used for my own needs:

Train the model:
C:\Users\rvunvulea>curl -X POST "https://rvfr.cognitiveservices.azure.com/formrecognizer/v1.0-preview/custom/train" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: 5b156fd6d9214fe782d09404073e077e" --data-ascii "{ \"source\": \""https://rvstoragetrain.blob.core.windows.net/train?sv=2019-02-02&ss=bfqt&srt=sco&sp=rwdlacup&se=2020-01-10T23:06:24Z&st=2019-12-05T15:06:24Z&spr=https&sig=ViAM63qYg44fmc2ntc4Bq%2BOcnYBm%2F1WRc4ZutvLjNxc%3D"\"}"
Output:
{"modelId":"7325d040-7d7a-4e77-ac09-ed740e7f2076","trainingDocuments":[{"documentName":"T1.pdf","pages":3,"errors":[],"status":"success"},{"documentName":"T2.pdf","pages":3,"errors":[],"status":"success"},{"documentName":"T3.pdf","pages":3,"errors":[],"status":"success"},{"documentName":"T4.pdf","pages":3,"errors":[],"status":"success"},{"documentName":"T5.pdf","pages":2,"errors":[],"status":"success"}],"errors":[]}

Model id returned in the previous steps needs to be used when you want to process a page.

Extract labels
curl -X POST "https://rvfr.cognitiveservices.azure.com/formrecognizer/v1.0-preview/custom/models/7325d040-7d7a-4e77-ac09-ed740e7f2076/analyze" -H "Content-Type: multipart/form-data" -F "form=@\"C:\1\T1.pdf\";type=application/pdf" -H "Ocp-Apim-Subscription-Key: 5b156fd6d9214fe782d09404073e077e"
Output: JSON result

Comments

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…