What is Document AI?
The Document AI API is a document understanding solution that takes unstructured data, such as documents, emails, and so on, and makes the data easier to understand, analyze, and consume. The API provides structure through content classification, entity extraction, advanced searching, and more.
In this tutorial, you focus on using the Document AI API with Python. The tutorial demonstrates how to parse a simple medical intake form.
What you'll learn
- How to enable the Document AI API
- How to authenticate API requests
- How to install the client library for Python
- How to parse data from a scanned form
What you'll need
Survey
How will you use this tutorial?
How would you rate your experience with Python?
How would you rate your experience with using Google Cloud services?
Self-paced environment setup
- Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or G Suite account, you must create one.)
Remember the project ID, a unique name across all Google Cloud projects. (Your name above has already been taken and will not work for you, sorry!). You must provide this ID later on as PROJECT_ID
.
- Next, you must enable billing in Cloud Console in order to use Google Cloud resources.
Be sure to to follow any instructions in the "Cleaning up" section. The section advises you how to shut down resources so you don't incur billing beyond this tutorial. New users of Google Cloud are eligible for the $300USD Free Trial program.
Start Cloud Shell
While Google Cloud you can operate Google Cloud remotely from your laptop, this codelab uses Google Cloud Shell, a command line environment running in the Cloud.
Activate Cloud Shell
- From the Cloud Console, click Activate Cloud Shell
.
If you've never started Cloud Shell before, you are presented with an intermediate screen (below the fold) describing what it is. If that's the case, click Continue (and you won't ever see it again). Here's what that one-time screen looks like:
It should only take a few moments to provision and connect to Cloud Shell.
Cloud Shell provides you with terminal access to a virtual machine hosted in the cloud. The virtual machine includes all the development tools that you'll need. It offers a persistent 5GB home directory and runs in Google Cloud, greatly enhancing network performance and authentication. Much, if not all, of your work in this codelab can be done with simply a browser or your Chromebook.
Once connected to Cloud Shell, you should see that you are already authenticated and that the project is already set to your project ID.
- Run the following command in Cloud Shell to confirm that you are authenticated:
gcloud auth list
Command output
Credentialed Accounts ACTIVE ACCOUNT * <my_account>@<my_domain.com> To set the active account, run: $ gcloud config set account `ACCOUNT`
gcloud config list project
Command output
[core] project = <PROJECT_ID>
If it is not, you can set it with this command:
gcloud config set project <PROJECT_ID>
Command output
Updated property [core/project].
Before you can begin using Document AI, you must enable the API. Open the Cloud Console in your browser.
- Click Navigation menu ☰ > APIs & Services > Library.
- Search for "Document AI API," then click Enable to use the API in your Google Cloud project
You must first create an instance of the Form Parser processor to use in the Document AI Platform for this tutorial.
- In the console, navigate to the Document AI Platform Overview
- Click Create Processor and select Form Parser
- Specify a processor name and select your region from the list.
- Click Create to create your processor
- Copy your processor ID. You must use this in your code later.
(Optional) You can test out your processor in the console by uploading a document. Click Upload Document and select a form to parse. You can download and use this sample form if you do not have one available to use.
Your output should look this:
In order to make requests to the Document AI API, you must use a Service Account. A Service Account belongs to your project and it is used by the Google Client Python library to make API requests. Like any other user account, a service account is represented by an email address. In this section, you will use the Cloud SDK to create a service account and then create credentials you need to authenticate as the service account.
First, set an environment variable with your PROJECT_ID
which you will use throughout this codelab:
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)
Next, create a new service account to access the Document AI API by using:
gcloud iam service-accounts create my-docai-sa \
--display-name "my-docai-service-account"
Next, create credentials that your Python code uses to login as your new service account. Create these credentials and save it as a JSON file "~/key.json" by using the following command:
gcloud iam service-accounts keys create ~/key.json \
--iam-account my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com
Finally, set the GOOGLE_APPLICATION_CREDENTIALS environment variable, which is used by the library to find your credentials. To read more about this form authentication, see the guide. The environment variable should be set to the full path of the credentials JSON file you created, by using:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"
We have a sample form to use stored in Google Cloud Storage. Use the following command to download it to your working directory.
gsutil cp gs://cloud-samples-data/documentai/form.pdf .
Confirm the file is downloaded to your cloudshell using the below command:
ls -ltr form.pdf
Install the client library:
pip3 install --upgrade google-cloud-documentai pip3 install --upgrade google-cloud-storage
You should see something like this:
... Installing collected packages: google-cloud-documentai Successfully installed google-cloud-documentai-0.3.0 . . Installing collected packages: google-cloud-storage Successfully installed google-cloud-storage-1.35.0
Now, you're ready to use the Document AI API!
Start Interactive Python
In this tutorial, you'll use an interactive Python interpreter called IPython. Start a session by running ipython
in Cloud Shell. This command runs the Python interpreter in an interactive session.
ipython
You should see something like this:
Python 3.7.3 (default, Jul 25 2020, 13:03:44) Type 'copyright', 'credits' or 'license' for more information IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help. In [1]:
In this step you make a process document call using the synchronous endpoint. For processing large amounts of documents at a time you can also use the asynchronous API, to learn more about using the Form Parser APIs, read the guide here.
Copy the following code into your iPython session:
project_id= 'YOUR_PROJECT_ID'
location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu'
processor_id = 'YOUR_PROCESSOR_ID' # Create processor in Cloud Console
file_path = 'form.pdf' # The local file in your current working directory
from google.cloud import documentai_v1beta3 as documentai
from google.cloud import storage
def process_document(
project_id=project_id, location=location, processor_id=processor_id, file_path=file_path
):
# Instantiates a client
client = documentai.DocumentProcessorServiceClient()
# The full resource name of the processor, e.g.:
# projects/project-id/locations/location/processor/processor-id
# You must create new processors in the Cloud Console first
name = f"projects/{project_id}/locations/{location}/processors/{processor_id}"
with open(file_path, "rb") as image:
image_content = image.read()
# Read the file into memory
document = {"content": image_content, "mime_type": "application/pdf"}
# Configure the process request
request = {"name": name, "document": document}
# Use the Document AI client to process the sample form
result = client.process_document(request=request)
document = result.document
document_text = document.text
print("Document processing complete.")
print("Text: {}".format(document_text))
Run your code now and you should see the text extracted and printed in your console. In the next steps, you extract structured data that can more easily stored in databases or used in other applications.
Call the function:
process_document()
Now you can extract the key-value pairs from the form and their corresponding confidence scores. The Document response object contains a list of pages from the input document. Each page
object contains a list of form fields and their locations in the text.
The following code iterates through each page and extracts and prints each key, value and confidence score.
At the bottom of your processDocument() function, paste the code below:
document_pages = document.pages
for page in document_pages:
print("Page Number:{}".format(page.page_number))
for form_field in page.form_fields:
fieldName=get_text(form_field.field_name,document)
nameConfidence = round(form_field.field_name.confidence,4)
fieldValue = get_text(form_field.field_value,document)
valueConfidence = round(form_field.field_value.confidence,4)
print(fieldName+fieldValue +" (Confidence Scores: "+str(nameConfidence)+", "+str(valueConfidence)+")")
def get_text(doc_element: dict, document: dict):
"""
Document AI identifies form fields by their offsets
in document text. This function converts offsets
to text snippets.
"""
response = ""
# If a text segment spans several lines, it will
# be stored in different text segments.
for segment in doc_element.text_anchor.text_segments:
start_index = (
int(segment.start_index)
if segment in doc_element.text_anchor.text_segments
else 0
)
end_index = int(segment.end_index)
response += document.text[start_index:end_index]
return response
Now run your code, call the function:
process_document()
You should see the following output if using our sample document:
Document processing complete.
Page Number:1
Marital Status: Single (Confidence Scores: 1.0000, 1.0000)
DOB: 09/04/1986 (Confidence Scores: 0.9999, 0.9999)
City: Towalo (Confidence Scores: 0.9996, 0.9996)
Address: 24 Barney Lane (Confidence Scores: 0.9994, 0.9994)
Referred By: None (Confidence Scores: 0.9968, 0.9968)
Phone #: (906) 917-3486 (Confidence Scores: 0.9961, 0.9961)
State: NJ (Confidence Scores: 0.9960, 0.9960)
Emergency Contact Phone: (906) 334-8926 (Confidence Scores: 0.9924, 0.9924)
Name: Sally Walker (Confidence Scores: 0.9922, 0.9922)
Congratulations, you've successfully used the Document AI API to extract data from a handwritten form. We encourage you to experiment with other form images
Clean Up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial:
- In the Cloud Console, go to the Manage resources page.
- In the project list, select your project then click Delete.
- In the dialog, type the project ID and then click Shut down to delete the project.