|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +# [START documentai_batch_process_documents_processor_version] |
| 17 | +import re |
| 18 | + |
| 19 | +from google.api_core.client_options import ClientOptions |
| 20 | +from google.cloud import documentai, storage |
| 21 | + |
| 22 | +# TODO(developer): Uncomment these variables before running the sample. |
| 23 | +# project_id = 'YOUR_PROJECT_ID' |
| 24 | +# location = 'YOUR_PROCESSOR_LOCATION' # Format is 'us' or 'eu' |
| 25 | +# processor_id = 'YOUR_PROCESSOR_ID' # Example: aeb8cea219b7c272 |
| 26 | +# processor_version_id = "YOUR_PROCESSOR_VERSION_ID" # Example: pretrained-ocr-v1.0-2020-09-23 |
| 27 | +# gcs_input_uri = "YOUR_INPUT_URI" # Format: gs://bucket/directory/file.pdf |
| 28 | +# input_mime_type = "application/pdf" |
| 29 | +# gcs_output_bucket = "YOUR_OUTPUT_BUCKET_NAME" # Format: gs://bucket |
| 30 | +# gcs_output_uri_prefix = "YOUR_OUTPUT_URI_PREFIX" # Format: directory/subdirectory/ |
| 31 | + |
| 32 | + |
| 33 | +def batch_process_documents_processor_version( |
| 34 | + project_id: str, |
| 35 | + location: str, |
| 36 | + processor_id: str, |
| 37 | + processor_version_id: str, |
| 38 | + gcs_input_uri: str, |
| 39 | + input_mime_type: str, |
| 40 | + gcs_output_bucket: str, |
| 41 | + gcs_output_uri_prefix: str, |
| 42 | + timeout: int = 300, |
| 43 | +): |
| 44 | + |
| 45 | + # You must set the api_endpoint if you use a location other than 'us', e.g.: |
| 46 | + opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com") |
| 47 | + |
| 48 | + client = documentai.DocumentProcessorServiceClient(client_options=opts) |
| 49 | + |
| 50 | + gcs_document = documentai.GcsDocument( |
| 51 | + gcs_uri=gcs_input_uri, mime_type=input_mime_type |
| 52 | + ) |
| 53 | + |
| 54 | + # Load GCS Input URI into a List of document files |
| 55 | + gcs_documents = documentai.GcsDocuments(documents=[gcs_document]) |
| 56 | + input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents) |
| 57 | + |
| 58 | + # NOTE: Alternatively, specify a GCS URI Prefix to process an entire directory |
| 59 | + # |
| 60 | + # gcs_input_uri = "gs://bucket/directory/" |
| 61 | + # gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri) |
| 62 | + # input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix) |
| 63 | + # |
| 64 | + |
| 65 | + # Cloud Storage URI for the Output Directory |
| 66 | + destination_uri = f"{gcs_output_bucket}/{gcs_output_uri_prefix}/" |
| 67 | + |
| 68 | + gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig( |
| 69 | + gcs_uri=destination_uri |
| 70 | + ) |
| 71 | + |
| 72 | + # Where to write results |
| 73 | + output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config) |
| 74 | + |
| 75 | + # The full resource name of the processor version |
| 76 | + # e.g. projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id} |
| 77 | + name = client.processor_version_path( |
| 78 | + project_id, location, processor_id, processor_version_id |
| 79 | + ) |
| 80 | + |
| 81 | + request = documentai.BatchProcessRequest( |
| 82 | + name=name, |
| 83 | + input_documents=input_config, |
| 84 | + document_output_config=output_config, |
| 85 | + ) |
| 86 | + |
| 87 | + # BatchProcess returns a Long Running Operation (LRO) |
| 88 | + operation = client.batch_process_documents(request) |
| 89 | + |
| 90 | + # Continually polls the operation until it is complete. |
| 91 | + # This could take some time for larger files |
| 92 | + # Format: projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID |
| 93 | + print(f"Waiting for operation {operation.operation.name} to complete...") |
| 94 | + operation.result(timeout=timeout) |
| 95 | + |
| 96 | + # NOTE: Can also use callbacks for asynchronous processing |
| 97 | + # |
| 98 | + # def my_callback(future): |
| 99 | + # result = future.result() |
| 100 | + # |
| 101 | + # operation.add_done_callback(my_callback) |
| 102 | + |
| 103 | + # Once the operation is complete, |
| 104 | + # get output document information from operation metadata |
| 105 | + metadata = documentai.BatchProcessMetadata(operation.metadata) |
| 106 | + |
| 107 | + if metadata.state != documentai.BatchProcessMetadata.State.SUCCEEDED: |
| 108 | + raise ValueError(f"Batch Process Failed: {metadata.state_message}") |
| 109 | + |
| 110 | + storage_client = storage.Client() |
| 111 | + |
| 112 | + print("Output files:") |
| 113 | + # One process per Input Document |
| 114 | + for process in metadata.individual_process_statuses: |
| 115 | + # output_gcs_destination format: gs://BUCKET/PREFIX/OPERATION_NUMBER/INPUT_FILE_NUMBER/ |
| 116 | + # The Cloud Storage API requires the bucket name and URI prefix separately |
| 117 | + matches = re.match(r"gs://(.*?)/(.*)", process.output_gcs_destination) |
| 118 | + if not matches: |
| 119 | + print( |
| 120 | + "Could not parse output GCS destination:", |
| 121 | + process.output_gcs_destination, |
| 122 | + ) |
| 123 | + continue |
| 124 | + |
| 125 | + output_bucket, output_prefix = matches.groups() |
| 126 | + |
| 127 | + # Get List of Document Objects from the Output Bucket |
| 128 | + output_blobs = storage_client.list_blobs(output_bucket, prefix=output_prefix) |
| 129 | + |
| 130 | + # Document AI may output multiple JSON files per source file |
| 131 | + for blob in output_blobs: |
| 132 | + # Document AI should only output JSON files to GCS |
| 133 | + if ".json" not in blob.name: |
| 134 | + print( |
| 135 | + f"Skipping non-supported file: {blob.name} - Mimetype: {blob.content_type}" |
| 136 | + ) |
| 137 | + continue |
| 138 | + |
| 139 | + # Download JSON File as bytes object and convert to Document Object |
| 140 | + print(f"Fetching {blob.name}") |
| 141 | + document = documentai.Document.from_json( |
| 142 | + blob.download_as_bytes(), ignore_unknown_fields=True |
| 143 | + ) |
| 144 | + |
| 145 | + # For a full list of Document object attributes, please reference this page: |
| 146 | + # https://cloud.google.com/python/docs/reference/documentai/latest/google.cloud.documentai_v1.types.Document |
| 147 | + |
| 148 | + # Read the text recognition output from the processor |
| 149 | + print("The document contains the following text:") |
| 150 | + print(document.text) |
| 151 | + |
| 152 | + |
| 153 | +# [END documentai_batch_process_documents_processor_version] |
0 commit comments