|
| 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_process_ocr_document] |
| 17 | + |
| 18 | +# TODO(developer): Uncomment these variables before running the sample. |
| 19 | +# project_id= 'YOUR_PROJECT_ID' |
| 20 | +# location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu' |
| 21 | +# processor_id = 'YOUR_PROCESSOR_ID' # Create processor in Cloud Console |
| 22 | +# file_path = '/path/to/local/pdf' |
| 23 | + |
| 24 | +def process_document_ocr_sample( |
| 25 | + project_id: str, location: str, processor_id: str, file_path: str |
| 26 | +) -> None: |
| 27 | + from google.cloud import documentai_v1beta3 as documentai |
| 28 | + |
| 29 | + # You must set the api_endpoint if you use a location other than 'us', e.g.: |
| 30 | + opts = {} |
| 31 | + if location == "eu": |
| 32 | + opts = {"api_endpoint": "eu-documentai.googleapis.com"} |
| 33 | + |
| 34 | + client = documentai.DocumentProcessorServiceClient(client_options=opts) |
| 35 | + |
| 36 | + # The full resource name of the processor, e.g.: |
| 37 | + # projects/project-id/locations/location/processor/processor-id |
| 38 | + # You must create new processors in the Cloud Console first |
| 39 | + name = f"projects/{project_id}/locations/{location}/processors/{processor_id}" |
| 40 | + |
| 41 | + with open(file_path, "rb") as image: |
| 42 | + image_content = image.read() |
| 43 | + |
| 44 | + # Read the file into memory |
| 45 | + document = {"content": image_content, "mime_type": "application/pdf"} |
| 46 | + |
| 47 | + # Configure the process request |
| 48 | + request = {"name": name, "raw_document": document} |
| 49 | + |
| 50 | + # Recognizes text entities in the PDF document |
| 51 | + result = client.process_document(request=request) |
| 52 | + |
| 53 | + print("Document processing complete.") |
| 54 | + |
| 55 | + # Read the text recognition output from the processor |
| 56 | + # For a full list of Document object attributes, please reference this page: https://googleapis.dev/python/documentai/latest/_modules/google/cloud/documentai_v1beta3/types/document.html#Document |
| 57 | + document = result.document |
| 58 | + text = document.text |
| 59 | + print(f"Full document text: {repr(text)}\n") |
| 60 | + print(f"There are {len(document.pages)} page(s) in this document.\n") |
| 61 | + |
| 62 | + for page in document.pages: |
| 63 | + print(f"Page {page.page_number}:") |
| 64 | + print_page_dimensions(page.dimension) |
| 65 | + print_detected_langauges(page.detected_languages) |
| 66 | + print_paragraphs(page.paragraphs, text) |
| 67 | + print_blocks(page.blocks, text) |
| 68 | + print_lines(page.lines, text) |
| 69 | + print_tokens(page.tokens, text) |
| 70 | + |
| 71 | + |
| 72 | +def print_page_dimensions(dimension: dict) -> None: |
| 73 | + print(f" Width: {str(dimension.width)}") |
| 74 | + print(f" Height: {str(dimension.height)}") |
| 75 | + |
| 76 | + |
| 77 | +def print_detected_langauges(detected_languages: dict) -> None: |
| 78 | + print(" Detected languages:") |
| 79 | + for lang in detected_languages: |
| 80 | + code = lang.language_code |
| 81 | + conf_percent = '{:.1%}'.format(lang.confidence) |
| 82 | + print(f" {code} ({conf_percent} confidence)") |
| 83 | + |
| 84 | + |
| 85 | +def print_paragraphs(paragraphs: dict, text: str) -> None: |
| 86 | + print(f" {len(paragraphs)} paragraphs detected:") |
| 87 | + first_paragraph_text = layout_to_text(paragraphs[0].layout, text) |
| 88 | + print(f" First paragraph text: {repr(first_paragraph_text)}") |
| 89 | + last_paragraph_text = layout_to_text(paragraphs[-1].layout, text) |
| 90 | + print(f" Last paragraph text: {repr(last_paragraph_text)}") |
| 91 | + |
| 92 | + |
| 93 | +def print_blocks(blocks: dict, text: str) -> None: |
| 94 | + print(f" {len(blocks)} blocks detected:") |
| 95 | + first_block_text = layout_to_text(blocks[0].layout, text) |
| 96 | + print(f" First text block: {repr(first_block_text)}") |
| 97 | + last_block_text = layout_to_text(blocks[-1].layout, text) |
| 98 | + print(f" Last text block: {repr(last_block_text)}") |
| 99 | + |
| 100 | + |
| 101 | +def print_lines(lines: dict, text: str) -> None: |
| 102 | + print(f" {len(lines)} lines detected:") |
| 103 | + first_line_text = layout_to_text(lines[0].layout, text) |
| 104 | + print(f" First line text: {repr(first_line_text)}") |
| 105 | + last_line_text = layout_to_text(lines[-1].layout, text) |
| 106 | + print(f" Last line text: {repr(last_line_text)}") |
| 107 | + |
| 108 | + |
| 109 | +def print_tokens(tokens: dict, text: str) -> None: |
| 110 | + print(f" {len(tokens)} tokens detected:") |
| 111 | + first_token_text = layout_to_text(tokens[0].layout, text) |
| 112 | + first_token_break_type = tokens[0].detected_break.type_.name |
| 113 | + print(f" First token text: {repr(first_token_text)}") |
| 114 | + print(f" First token break type: {repr(first_token_break_type)}") |
| 115 | + last_token_text = layout_to_text(tokens[-1].layout, text) |
| 116 | + last_token_break_type = tokens[-1].detected_break.type_.name |
| 117 | + print(f" Last token text: {repr(last_token_text)}") |
| 118 | + print(f" Last token break type: {repr(last_token_break_type)}") |
| 119 | + |
| 120 | + |
| 121 | +def layout_to_text(layout: dict, text: str) -> str: |
| 122 | + """ |
| 123 | + Document AI identifies text in different parts of the document by their |
| 124 | + offsets in the entirity of the document's text. This function converts |
| 125 | + offsets to a string. |
| 126 | + """ |
| 127 | + response = "" |
| 128 | + # If a text segment spans several lines, it will |
| 129 | + # be stored in different text segments. |
| 130 | + for segment in layout.text_anchor.text_segments: |
| 131 | + start_index = ( |
| 132 | + int(segment.start_index) |
| 133 | + if segment in layout.text_anchor.text_segments |
| 134 | + else 0 |
| 135 | + ) |
| 136 | + end_index = int(segment.end_index) |
| 137 | + response += text[start_index:end_index] |
| 138 | + return response |
| 139 | + |
| 140 | + |
| 141 | +# [END documentai_process_ocr_document] |
0 commit comments