google-cloud-documentai-toolbox 0.15.0a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,439 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2023 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ """Document.proto converters."""
17
+
18
+ from concurrent import futures
19
+ import os
20
+ import time
21
+ from typing import Dict, List, Optional, Set, Tuple
22
+
23
+ from google.api_core.client_options import ClientOptions
24
+
25
+ from google.cloud import documentai
26
+ from google.cloud.documentai_toolbox import constants
27
+ from google.cloud.documentai_toolbox.converters.config import bbox_conversion
28
+ from google.cloud.documentai_toolbox.converters.config.block import Block
29
+ from google.cloud.documentai_toolbox.utilities import gcs_utilities
30
+
31
+
32
+ def _get_base_ocr(
33
+ project_id: str,
34
+ location: str,
35
+ processor_id: str,
36
+ file_bytes: bytes,
37
+ mime_type: str,
38
+ field_mask: Optional[str] = None,
39
+ processor_version_id: Optional[str] = None,
40
+ ) -> documentai.Document:
41
+ r"""Returns `documentai.Document` from OCR processor.
42
+
43
+ Args:
44
+ project_id (str):
45
+ Required.
46
+ location (str):
47
+ Required.
48
+ processor_id (str):
49
+ Required.
50
+ file_bytes (bytes):
51
+ Required. The bytes of the original pdf.
52
+ mime_type (str):
53
+ Required. Usually `application/pdf`.
54
+ field_mask (Optional[str]):
55
+ Optional. Specifies which fields to include in the `Document` output.
56
+ processor_version_id (Optional[str]):
57
+ Optional. Specifies the processor version to use.
58
+
59
+ Returns:
60
+ documentai.Document:
61
+ A documentai.Document from OCR processor.
62
+
63
+ """
64
+ client = documentai.DocumentProcessorServiceClient(
65
+ client_options=ClientOptions(
66
+ api_endpoint=f"{location}-documentai.googleapis.com"
67
+ ),
68
+ client_info=gcs_utilities._get_client_info(),
69
+ )
70
+
71
+ name = (
72
+ client.processor_version_path(
73
+ project_id, location, processor_id, processor_version_id
74
+ )
75
+ if processor_version_id
76
+ else client.processor_path(project_id, location, processor_id)
77
+ )
78
+
79
+ result = client.process_document(
80
+ request=documentai.ProcessRequest(
81
+ name=name,
82
+ raw_document=documentai.RawDocument(
83
+ content=file_bytes, mime_type=mime_type
84
+ ),
85
+ field_mask=field_mask,
86
+ )
87
+ )
88
+ return result.document
89
+
90
+
91
+ def _get_entity_content(
92
+ blocks: List[Block], docproto: documentai.Document
93
+ ) -> List[documentai.Document.Entity]:
94
+ r"""Returns a list of documentai.Document entities.
95
+
96
+ Args:
97
+ blocks (List[Block]):
98
+ Required.List of blocks from original annotation.
99
+ docproto (documentai.Document):
100
+ Required.The ocr docproto.
101
+ Returns:
102
+ List[documentai.Document.Entity]:
103
+ A list of documentai.Document entities.
104
+ """
105
+ entities: List[documentai.Document.Entity] = []
106
+
107
+ for entity_id, block in enumerate(blocks):
108
+ docai_entity = documentai.Document.Entity(
109
+ type=block.type_,
110
+ mention_text=block.text,
111
+ id=str(entity_id),
112
+ confidence=block.confidence if block.confidence else None,
113
+ )
114
+
115
+ if block.bounding_box:
116
+ bounding_box = bbox_conversion.convert_bbox_to_docproto_bbox(block)
117
+ page_number = int(block.page_number) - 1 if block.page_number else 0
118
+ page = docproto.pages[page_number]
119
+
120
+ docai_entity.text_anchor = bbox_conversion.get_text_anchor_in_bbox(
121
+ bounding_box, page
122
+ )
123
+ docai_entity.text_anchor.content = block.text
124
+ docai_entity.page_anchor = documentai.Document.PageAnchor(
125
+ page_refs=[
126
+ documentai.Document.PageAnchor.PageRef(bounding_poly=bounding_box)
127
+ ]
128
+ )
129
+
130
+ entities.append(docai_entity)
131
+
132
+ return entities
133
+
134
+
135
+ def _convert_to_docproto_with_config(
136
+ annotated_bytes: bytes,
137
+ config_bytes: bytes,
138
+ document_bytes: bytes,
139
+ project_id: str,
140
+ location: str,
141
+ processor_id: str,
142
+ wait_time: int = 1,
143
+ max_retries: int = 6,
144
+ name: str = "",
145
+ ) -> Optional[documentai.Document]:
146
+ r"""Converts a single document to docproto.
147
+
148
+ Args:
149
+ annotated_bytes (bytes):
150
+ Required.The bytes of the annotated data.
151
+ config_bytes (bytes):
152
+ Required.The bytes of config data.
153
+ document_bytes (bytes):
154
+ Required. The bytes of the original pdf.
155
+ project_id (str):
156
+ Required.
157
+ location (str):
158
+ Required.
159
+ processor_id (str):
160
+ Required.
161
+ wait_time (str):
162
+ Optional. The number of seconds needed to wait if an error occured.
163
+ max_retries (str):
164
+ Optional. Maximum times to retry before stopping.
165
+ name (str):
166
+ Optional. Name of the document to be converted. This is used for logging.
167
+
168
+ Returns:
169
+ Optional[documentai.Document]:
170
+ documentai.Document object. Returns None if the conversion fails.
171
+
172
+ TODO: Depending on input type you will need to modify load_blocks.
173
+ Depending on input format, if your annotated data is not separate from the base OCR data you will need to modify _get_entity_content
174
+ Depending on input BoundingBox, if the input BoundingBox object is like https://cloud.google.com/document-ai/docs/reference/rest/v1/Document#BoundingPoly then you will need to
175
+ modify bbox_conversion.convert_bbox_to_docproto_bbox since the objects are different.
176
+ """
177
+ for i in range(max_retries):
178
+ try:
179
+ base_docproto = _get_base_ocr(
180
+ project_id=project_id,
181
+ location=location,
182
+ processor_id=processor_id,
183
+ file_bytes=document_bytes,
184
+ mime_type=constants.PDF_MIMETYPE,
185
+ )
186
+
187
+ blocks = Block.load_blocks_from_schema(
188
+ input_data=annotated_bytes,
189
+ input_config=config_bytes,
190
+ base_docproto=base_docproto,
191
+ )
192
+
193
+ base_docproto.entities = _get_entity_content(blocks, base_docproto)
194
+
195
+ print(f"Converted: {name}", end="\r")
196
+ return base_docproto
197
+
198
+ except Exception as e:
199
+ print(e)
200
+ print(f"Could Not Convert {name}\nretrying")
201
+ time.sleep(wait_time + i)
202
+
203
+ return None
204
+
205
+
206
+ def _get_bytes(
207
+ gcs_uri: str,
208
+ annotation_file_prefix: str,
209
+ config_file_prefix: str,
210
+ config_path: Optional[str] = None,
211
+ ) -> Tuple[bytes, bytes, bytes, str]:
212
+ r"""Downloads documents and returns them as bytes.
213
+
214
+ Args:
215
+ gcs_uri (str):
216
+ Required: The fully-qualified Google Cloud Storage URI.
217
+
218
+ Format: `gs://{bucket_name}/{optional_folder}/{target_folder}`
219
+ annotation_file_prefix (str):
220
+ Required. The prefix to search for annotation file.
221
+ config_file_prefix (str):
222
+ Required. The prefix to search for config file.
223
+ config_path (str):
224
+ Optional. The gcs path to a config file. This should be used when there is a single config file.
225
+
226
+ Returns:
227
+ Tuple[bytes, bytes, bytes, str].
228
+ Annotation, Document PDF, Config File, Directory Name.
229
+
230
+ """
231
+ blobs = gcs_utilities.get_blobs(gcs_uri=gcs_uri)
232
+
233
+ try:
234
+ for blob in blobs:
235
+ if blob.name.endswith("/"):
236
+ continue
237
+ file_name = os.path.basename(blob.name)
238
+ if annotation_file_prefix in file_name:
239
+ annotation_blob = blob
240
+ elif config_file_prefix in file_name:
241
+ metadata_blob = blob
242
+ elif constants.PDF_EXTENSION in file_name:
243
+ doc_blob = blob
244
+
245
+ if config_path:
246
+ metadata_blob = gcs_utilities.get_blob(config_path)
247
+
248
+ directory_name = os.path.basename(gcs_uri)
249
+ print(f"Downloaded: {directory_name}", end="\r")
250
+
251
+ return (
252
+ annotation_blob.download_as_bytes(),
253
+ doc_blob.download_as_bytes(),
254
+ metadata_blob.download_as_bytes(),
255
+ directory_name,
256
+ )
257
+ except Exception as e:
258
+ raise e
259
+
260
+
261
+ def _get_files(
262
+ blob_list: List, config_path: Optional[str] = None
263
+ ) -> List[futures.Future]:
264
+ r"""Returns a list of Futures of documents as bytes.
265
+
266
+ Args:
267
+ blob_list (List[storage.blob.Blob]):
268
+ Required. The list of Futures from _get_files.
269
+ config_path (Optional[str]):
270
+ Optional. The configuration path.
271
+ Returns:
272
+ List[futures.Future]:
273
+ A list of Futures.
274
+
275
+ """
276
+
277
+ download_pool = futures.ThreadPoolExecutor(max_workers=10)
278
+
279
+ dirs = {
280
+ gcs_utilities.create_gcs_uri(blob.bucket.name, os.path.dirname(blob.name))
281
+ for blob in blob_list
282
+ }
283
+
284
+ print("-------- Downloading Started --------")
285
+ return [
286
+ download_pool.submit(
287
+ _get_bytes,
288
+ dir,
289
+ "annotation",
290
+ "config",
291
+ config_path,
292
+ )
293
+ for dir in dirs
294
+ ]
295
+
296
+
297
+ def _get_docproto_files(
298
+ futures_list: List[futures.Future],
299
+ project_id: str,
300
+ location: str,
301
+ processor_id: str,
302
+ ) -> Tuple[Dict[str, str], Set[str], List[str]]:
303
+ r"""Returns converted document.proto, unique entity types, and documents that were not converted.
304
+
305
+ Args:
306
+ futures_list (List[futures.Future]):
307
+ Required. The list of Futures from _get_files.
308
+ project_id (str):
309
+ Required. The project ID.
310
+ location (str):
311
+ Required. The location.
312
+ processor_id (str):
313
+ Required. The processor ID.
314
+
315
+ Returns:
316
+ Tuple[dict, set, list]:
317
+ Converted document.proto, unique entity types, and documents that were not converted.
318
+
319
+ """
320
+ files: Dict[str, str] = {}
321
+ unique_types: Set[str] = set()
322
+ did_not_convert: List[str] = []
323
+
324
+ for future in futures_list:
325
+ annotated_bytes, document_bytes, config_bytes, name = future.result()
326
+ docproto = _convert_to_docproto_with_config(
327
+ annotated_bytes=annotated_bytes,
328
+ document_bytes=document_bytes,
329
+ config_bytes=config_bytes,
330
+ project_id=project_id,
331
+ location=location,
332
+ processor_id=processor_id,
333
+ name=name,
334
+ )
335
+
336
+ if docproto is None:
337
+ did_not_convert.append(name)
338
+ continue
339
+
340
+ unique_types.update(entity.type_ for entity in docproto.entities)
341
+ files[name] = documentai.Document.to_json(docproto)
342
+
343
+ return files, unique_types, did_not_convert
344
+
345
+
346
+ def _upload(
347
+ files: dict,
348
+ gcs_output_path: str,
349
+ ) -> None:
350
+ r"""Upload converted document.proto to gcs location.
351
+
352
+ Args:
353
+ files (dict):
354
+ Required. The document.proto files to upload.
355
+ gcs_output_path (str):
356
+ Required. The gcs path to the folder to upload the converted docproto documents to.
357
+
358
+ Format: `gs://{bucket}/{optional_folder}`
359
+ Returns:
360
+ None.
361
+
362
+ """
363
+ upload_pool = futures.ThreadPoolExecutor(max_workers=10)
364
+
365
+ print("-------- Uploading Started --------")
366
+ uploads = [
367
+ upload_pool.submit(
368
+ gcs_utilities.upload_file,
369
+ gcs_output_path,
370
+ f"{name}{constants.JSON_EXTENSION}",
371
+ content,
372
+ )
373
+ for name, content in files.items()
374
+ if "config" not in name and "annotations" not in name
375
+ ]
376
+
377
+ futures.wait(uploads)
378
+
379
+
380
+ def convert_from_config(
381
+ project_id: str,
382
+ location: str,
383
+ processor_id: str,
384
+ gcs_input_path: str,
385
+ gcs_output_path: str,
386
+ config_path: Optional[str] = None,
387
+ ) -> None:
388
+ r"""Converts all documents in gcs_input_path to docproto using configs.
389
+
390
+ Args:
391
+ project_id (str):
392
+ Required.
393
+ location (str):
394
+ Required.
395
+ processor_id (str):
396
+ Required.
397
+ gcs_input_path (str):
398
+ Required. The gcs path to the folder containing all non docproto documents.
399
+
400
+ Format: `gs://{bucket}/{optional_folder}`
401
+ gcs_output_path (str):
402
+ Required. The gcs path to the folder to upload the converted docproto documents to.
403
+
404
+ Format: `gs://{bucket}/{optional_folder}`
405
+ config_path:
406
+ Optional. The gcs path to a single config file. This will work if all the documents in gcs_input_path are of the same config type.
407
+
408
+ Format: `gs://{bucket}/{optional_folder}/config.json`
409
+ Returns:
410
+ None.
411
+
412
+ """
413
+ blob_list = gcs_utilities.get_blobs(
414
+ gcs_uri=gcs_input_path, module="config-converter"
415
+ )
416
+ downloads = _get_files(
417
+ blob_list=blob_list,
418
+ config_path=config_path,
419
+ )
420
+
421
+ futures_list, _ = futures.wait(downloads)
422
+
423
+ print("-------- Finished Downloading --------")
424
+
425
+ print("-------- Converting Started --------")
426
+ files, labels, did_not_convert = _get_docproto_files(
427
+ futures_list, project_id, location, processor_id
428
+ )
429
+
430
+ print("-------- Finished Converting --------")
431
+ if did_not_convert:
432
+ print(f"Did not convert {len(did_not_convert)} documents")
433
+ print(did_not_convert)
434
+
435
+ _upload(files, gcs_output_path)
436
+
437
+ print("-------- Finished Uploading --------")
438
+ print("-------- Schema Information --------")
439
+ print(f"Unique Entity Types: {labels}")