nv-ingest-api 26.1.0rc4__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.

Potentially problematic release.


This version of nv-ingest-api might be problematic. Click here for more details.

Files changed (177) hide show
  1. nv_ingest_api/__init__.py +3 -0
  2. nv_ingest_api/interface/__init__.py +218 -0
  3. nv_ingest_api/interface/extract.py +977 -0
  4. nv_ingest_api/interface/mutate.py +154 -0
  5. nv_ingest_api/interface/store.py +200 -0
  6. nv_ingest_api/interface/transform.py +382 -0
  7. nv_ingest_api/interface/utility.py +186 -0
  8. nv_ingest_api/internal/__init__.py +0 -0
  9. nv_ingest_api/internal/enums/__init__.py +3 -0
  10. nv_ingest_api/internal/enums/common.py +550 -0
  11. nv_ingest_api/internal/extract/__init__.py +3 -0
  12. nv_ingest_api/internal/extract/audio/__init__.py +3 -0
  13. nv_ingest_api/internal/extract/audio/audio_extraction.py +202 -0
  14. nv_ingest_api/internal/extract/docx/__init__.py +5 -0
  15. nv_ingest_api/internal/extract/docx/docx_extractor.py +232 -0
  16. nv_ingest_api/internal/extract/docx/engines/__init__.py +0 -0
  17. nv_ingest_api/internal/extract/docx/engines/docxreader_helpers/__init__.py +3 -0
  18. nv_ingest_api/internal/extract/docx/engines/docxreader_helpers/docx_helper.py +127 -0
  19. nv_ingest_api/internal/extract/docx/engines/docxreader_helpers/docxreader.py +971 -0
  20. nv_ingest_api/internal/extract/html/__init__.py +3 -0
  21. nv_ingest_api/internal/extract/html/html_extractor.py +84 -0
  22. nv_ingest_api/internal/extract/image/__init__.py +3 -0
  23. nv_ingest_api/internal/extract/image/chart_extractor.py +375 -0
  24. nv_ingest_api/internal/extract/image/image_extractor.py +208 -0
  25. nv_ingest_api/internal/extract/image/image_helpers/__init__.py +3 -0
  26. nv_ingest_api/internal/extract/image/image_helpers/common.py +433 -0
  27. nv_ingest_api/internal/extract/image/infographic_extractor.py +290 -0
  28. nv_ingest_api/internal/extract/image/ocr_extractor.py +407 -0
  29. nv_ingest_api/internal/extract/image/table_extractor.py +391 -0
  30. nv_ingest_api/internal/extract/pdf/__init__.py +3 -0
  31. nv_ingest_api/internal/extract/pdf/engines/__init__.py +19 -0
  32. nv_ingest_api/internal/extract/pdf/engines/adobe.py +484 -0
  33. nv_ingest_api/internal/extract/pdf/engines/llama.py +246 -0
  34. nv_ingest_api/internal/extract/pdf/engines/nemotron_parse.py +598 -0
  35. nv_ingest_api/internal/extract/pdf/engines/pdf_helpers/__init__.py +166 -0
  36. nv_ingest_api/internal/extract/pdf/engines/pdfium.py +652 -0
  37. nv_ingest_api/internal/extract/pdf/engines/tika.py +96 -0
  38. nv_ingest_api/internal/extract/pdf/engines/unstructured_io.py +426 -0
  39. nv_ingest_api/internal/extract/pdf/pdf_extractor.py +74 -0
  40. nv_ingest_api/internal/extract/pptx/__init__.py +5 -0
  41. nv_ingest_api/internal/extract/pptx/engines/__init__.py +0 -0
  42. nv_ingest_api/internal/extract/pptx/engines/pptx_helper.py +968 -0
  43. nv_ingest_api/internal/extract/pptx/pptx_extractor.py +210 -0
  44. nv_ingest_api/internal/meta/__init__.py +3 -0
  45. nv_ingest_api/internal/meta/udf.py +232 -0
  46. nv_ingest_api/internal/mutate/__init__.py +3 -0
  47. nv_ingest_api/internal/mutate/deduplicate.py +110 -0
  48. nv_ingest_api/internal/mutate/filter.py +133 -0
  49. nv_ingest_api/internal/primitives/__init__.py +0 -0
  50. nv_ingest_api/internal/primitives/control_message_task.py +16 -0
  51. nv_ingest_api/internal/primitives/ingest_control_message.py +307 -0
  52. nv_ingest_api/internal/primitives/nim/__init__.py +9 -0
  53. nv_ingest_api/internal/primitives/nim/default_values.py +14 -0
  54. nv_ingest_api/internal/primitives/nim/model_interface/__init__.py +3 -0
  55. nv_ingest_api/internal/primitives/nim/model_interface/cached.py +274 -0
  56. nv_ingest_api/internal/primitives/nim/model_interface/decorators.py +56 -0
  57. nv_ingest_api/internal/primitives/nim/model_interface/deplot.py +270 -0
  58. nv_ingest_api/internal/primitives/nim/model_interface/helpers.py +338 -0
  59. nv_ingest_api/internal/primitives/nim/model_interface/nemotron_parse.py +239 -0
  60. nv_ingest_api/internal/primitives/nim/model_interface/ocr.py +776 -0
  61. nv_ingest_api/internal/primitives/nim/model_interface/parakeet.py +367 -0
  62. nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py +129 -0
  63. nv_ingest_api/internal/primitives/nim/model_interface/vlm.py +177 -0
  64. nv_ingest_api/internal/primitives/nim/model_interface/yolox.py +1681 -0
  65. nv_ingest_api/internal/primitives/nim/nim_client.py +801 -0
  66. nv_ingest_api/internal/primitives/nim/nim_model_interface.py +126 -0
  67. nv_ingest_api/internal/primitives/tracing/__init__.py +0 -0
  68. nv_ingest_api/internal/primitives/tracing/latency.py +69 -0
  69. nv_ingest_api/internal/primitives/tracing/logging.py +96 -0
  70. nv_ingest_api/internal/primitives/tracing/tagging.py +288 -0
  71. nv_ingest_api/internal/schemas/__init__.py +3 -0
  72. nv_ingest_api/internal/schemas/extract/__init__.py +3 -0
  73. nv_ingest_api/internal/schemas/extract/extract_audio_schema.py +133 -0
  74. nv_ingest_api/internal/schemas/extract/extract_chart_schema.py +144 -0
  75. nv_ingest_api/internal/schemas/extract/extract_docx_schema.py +129 -0
  76. nv_ingest_api/internal/schemas/extract/extract_html_schema.py +34 -0
  77. nv_ingest_api/internal/schemas/extract/extract_image_schema.py +126 -0
  78. nv_ingest_api/internal/schemas/extract/extract_infographic_schema.py +137 -0
  79. nv_ingest_api/internal/schemas/extract/extract_ocr_schema.py +137 -0
  80. nv_ingest_api/internal/schemas/extract/extract_pdf_schema.py +220 -0
  81. nv_ingest_api/internal/schemas/extract/extract_pptx_schema.py +128 -0
  82. nv_ingest_api/internal/schemas/extract/extract_table_schema.py +137 -0
  83. nv_ingest_api/internal/schemas/message_brokers/__init__.py +3 -0
  84. nv_ingest_api/internal/schemas/message_brokers/message_broker_client_schema.py +37 -0
  85. nv_ingest_api/internal/schemas/message_brokers/request_schema.py +34 -0
  86. nv_ingest_api/internal/schemas/message_brokers/response_schema.py +19 -0
  87. nv_ingest_api/internal/schemas/meta/__init__.py +3 -0
  88. nv_ingest_api/internal/schemas/meta/base_model_noext.py +11 -0
  89. nv_ingest_api/internal/schemas/meta/ingest_job_schema.py +355 -0
  90. nv_ingest_api/internal/schemas/meta/metadata_schema.py +394 -0
  91. nv_ingest_api/internal/schemas/meta/udf.py +23 -0
  92. nv_ingest_api/internal/schemas/mixins.py +39 -0
  93. nv_ingest_api/internal/schemas/mutate/__init__.py +3 -0
  94. nv_ingest_api/internal/schemas/mutate/mutate_image_dedup_schema.py +16 -0
  95. nv_ingest_api/internal/schemas/store/__init__.py +3 -0
  96. nv_ingest_api/internal/schemas/store/store_embedding_schema.py +28 -0
  97. nv_ingest_api/internal/schemas/store/store_image_schema.py +45 -0
  98. nv_ingest_api/internal/schemas/transform/__init__.py +3 -0
  99. nv_ingest_api/internal/schemas/transform/transform_image_caption_schema.py +36 -0
  100. nv_ingest_api/internal/schemas/transform/transform_image_filter_schema.py +17 -0
  101. nv_ingest_api/internal/schemas/transform/transform_text_embedding_schema.py +48 -0
  102. nv_ingest_api/internal/schemas/transform/transform_text_splitter_schema.py +24 -0
  103. nv_ingest_api/internal/store/__init__.py +3 -0
  104. nv_ingest_api/internal/store/embed_text_upload.py +236 -0
  105. nv_ingest_api/internal/store/image_upload.py +251 -0
  106. nv_ingest_api/internal/transform/__init__.py +3 -0
  107. nv_ingest_api/internal/transform/caption_image.py +219 -0
  108. nv_ingest_api/internal/transform/embed_text.py +702 -0
  109. nv_ingest_api/internal/transform/split_text.py +182 -0
  110. nv_ingest_api/util/__init__.py +3 -0
  111. nv_ingest_api/util/control_message/__init__.py +0 -0
  112. nv_ingest_api/util/control_message/validators.py +47 -0
  113. nv_ingest_api/util/converters/__init__.py +0 -0
  114. nv_ingest_api/util/converters/bytetools.py +78 -0
  115. nv_ingest_api/util/converters/containers.py +65 -0
  116. nv_ingest_api/util/converters/datetools.py +90 -0
  117. nv_ingest_api/util/converters/dftools.py +127 -0
  118. nv_ingest_api/util/converters/formats.py +64 -0
  119. nv_ingest_api/util/converters/type_mappings.py +27 -0
  120. nv_ingest_api/util/dataloader/__init__.py +9 -0
  121. nv_ingest_api/util/dataloader/dataloader.py +409 -0
  122. nv_ingest_api/util/detectors/__init__.py +5 -0
  123. nv_ingest_api/util/detectors/language.py +38 -0
  124. nv_ingest_api/util/exception_handlers/__init__.py +0 -0
  125. nv_ingest_api/util/exception_handlers/converters.py +72 -0
  126. nv_ingest_api/util/exception_handlers/decorators.py +429 -0
  127. nv_ingest_api/util/exception_handlers/detectors.py +74 -0
  128. nv_ingest_api/util/exception_handlers/pdf.py +116 -0
  129. nv_ingest_api/util/exception_handlers/schemas.py +68 -0
  130. nv_ingest_api/util/image_processing/__init__.py +5 -0
  131. nv_ingest_api/util/image_processing/clustering.py +260 -0
  132. nv_ingest_api/util/image_processing/processing.py +177 -0
  133. nv_ingest_api/util/image_processing/table_and_chart.py +504 -0
  134. nv_ingest_api/util/image_processing/transforms.py +850 -0
  135. nv_ingest_api/util/imports/__init__.py +3 -0
  136. nv_ingest_api/util/imports/callable_signatures.py +108 -0
  137. nv_ingest_api/util/imports/dynamic_resolvers.py +158 -0
  138. nv_ingest_api/util/introspection/__init__.py +3 -0
  139. nv_ingest_api/util/introspection/class_inspect.py +145 -0
  140. nv_ingest_api/util/introspection/function_inspect.py +65 -0
  141. nv_ingest_api/util/logging/__init__.py +0 -0
  142. nv_ingest_api/util/logging/configuration.py +102 -0
  143. nv_ingest_api/util/logging/sanitize.py +84 -0
  144. nv_ingest_api/util/message_brokers/__init__.py +3 -0
  145. nv_ingest_api/util/message_brokers/qos_scheduler.py +283 -0
  146. nv_ingest_api/util/message_brokers/simple_message_broker/__init__.py +9 -0
  147. nv_ingest_api/util/message_brokers/simple_message_broker/broker.py +465 -0
  148. nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py +71 -0
  149. nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py +455 -0
  150. nv_ingest_api/util/metadata/__init__.py +5 -0
  151. nv_ingest_api/util/metadata/aggregators.py +516 -0
  152. nv_ingest_api/util/multi_processing/__init__.py +8 -0
  153. nv_ingest_api/util/multi_processing/mp_pool_singleton.py +200 -0
  154. nv_ingest_api/util/nim/__init__.py +161 -0
  155. nv_ingest_api/util/pdf/__init__.py +3 -0
  156. nv_ingest_api/util/pdf/pdfium.py +428 -0
  157. nv_ingest_api/util/schema/__init__.py +3 -0
  158. nv_ingest_api/util/schema/schema_validator.py +10 -0
  159. nv_ingest_api/util/service_clients/__init__.py +3 -0
  160. nv_ingest_api/util/service_clients/client_base.py +86 -0
  161. nv_ingest_api/util/service_clients/kafka/__init__.py +3 -0
  162. nv_ingest_api/util/service_clients/redis/__init__.py +3 -0
  163. nv_ingest_api/util/service_clients/redis/redis_client.py +983 -0
  164. nv_ingest_api/util/service_clients/rest/__init__.py +0 -0
  165. nv_ingest_api/util/service_clients/rest/rest_client.py +595 -0
  166. nv_ingest_api/util/string_processing/__init__.py +51 -0
  167. nv_ingest_api/util/string_processing/configuration.py +682 -0
  168. nv_ingest_api/util/string_processing/yaml.py +109 -0
  169. nv_ingest_api/util/system/__init__.py +0 -0
  170. nv_ingest_api/util/system/hardware_info.py +594 -0
  171. nv_ingest_api-26.1.0rc4.dist-info/METADATA +237 -0
  172. nv_ingest_api-26.1.0rc4.dist-info/RECORD +177 -0
  173. nv_ingest_api-26.1.0rc4.dist-info/WHEEL +5 -0
  174. nv_ingest_api-26.1.0rc4.dist-info/licenses/LICENSE +201 -0
  175. nv_ingest_api-26.1.0rc4.dist-info/top_level.txt +2 -0
  176. udfs/__init__.py +5 -0
  177. udfs/llm_summarizer_udf.py +259 -0
@@ -0,0 +1,391 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024-25, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from typing import Any, Union
8
+ from typing import Dict
9
+ from typing import List
10
+ from typing import Optional
11
+ from typing import Tuple
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from nv_ingest_api.internal.schemas.meta.ingest_job_schema import IngestTaskTableExtraction
17
+ from nv_ingest_api.internal.enums.common import TableFormatEnum
18
+ from nv_ingest_api.internal.primitives.nim.model_interface.ocr import PaddleOCRModelInterface
19
+ from nv_ingest_api.internal.primitives.nim.model_interface.ocr import NemoRetrieverOCRModelInterface
20
+ from nv_ingest_api.internal.primitives.nim.model_interface.ocr import get_ocr_model_name
21
+ from nv_ingest_api.internal.primitives.nim import NimClient
22
+ from nv_ingest_api.internal.schemas.extract.extract_table_schema import TableExtractorSchema
23
+ from nv_ingest_api.util.image_processing.table_and_chart import join_yolox_table_structure_and_ocr_output
24
+ from nv_ingest_api.util.image_processing.table_and_chart import convert_ocr_response_to_psuedo_markdown
25
+ from nv_ingest_api.internal.primitives.nim.model_interface.yolox import YoloxTableStructureModelInterface
26
+ from nv_ingest_api.util.image_processing.transforms import base64_to_numpy
27
+ from nv_ingest_api.util.nim import create_inference_client
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ PADDLE_MIN_WIDTH = 32
32
+ PADDLE_MIN_HEIGHT = 32
33
+
34
+
35
+ def _filter_valid_images(
36
+ base64_images: List[str],
37
+ ) -> Tuple[List[str], List[np.ndarray], List[int]]:
38
+ """
39
+ Filter base64-encoded images by their dimensions.
40
+
41
+ Returns three lists:
42
+ - valid_images: The base64 strings that meet minimum size requirements.
43
+ - valid_arrays: The corresponding numpy arrays.
44
+ - valid_indices: The original indices in the input list.
45
+ """
46
+ valid_images: List[str] = []
47
+ valid_arrays: List[np.ndarray] = []
48
+ valid_indices: List[int] = []
49
+
50
+ for i, img in enumerate(base64_images):
51
+ array = base64_to_numpy(img)
52
+ height, width = array.shape[0], array.shape[1]
53
+ if width >= PADDLE_MIN_WIDTH and height >= PADDLE_MIN_HEIGHT:
54
+ valid_images.append(img)
55
+ valid_arrays.append(array)
56
+ valid_indices.append(i)
57
+ else:
58
+ # Image is too small; skip it.
59
+ continue
60
+
61
+ return valid_images, valid_arrays, valid_indices
62
+
63
+
64
+ def _run_inference(
65
+ enable_yolox: bool,
66
+ yolox_client: Any,
67
+ ocr_client: Any,
68
+ ocr_model_name: str,
69
+ valid_arrays: List[np.ndarray],
70
+ valid_images: List[str],
71
+ trace_info: Optional[Dict] = None,
72
+ ) -> Tuple[List[Any], List[Any]]:
73
+ """
74
+ Run inference concurrently for YOLOX (if enabled) and Paddle.
75
+
76
+ Returns a tuple of (yolox_results, ocr_results).
77
+ """
78
+ data_ocr = {"base64_images": valid_images}
79
+ if enable_yolox:
80
+ data_yolox = {"images": valid_arrays}
81
+ future_yolox_kwargs = dict(
82
+ data=data_yolox,
83
+ model_name="yolox_ensemble",
84
+ stage_name="table_extraction",
85
+ max_batch_size=8,
86
+ input_names=["INPUT_IMAGES", "THRESHOLDS"],
87
+ dtypes=["BYTES", "FP32"],
88
+ output_names=["OUTPUT"],
89
+ trace_info=trace_info,
90
+ )
91
+
92
+ future_ocr_kwargs = dict(
93
+ data=data_ocr,
94
+ stage_name="table_extraction",
95
+ trace_info=trace_info,
96
+ )
97
+ if ocr_model_name == "paddle":
98
+ future_ocr_kwargs.update(
99
+ model_name="paddle",
100
+ max_batch_size=1 if ocr_client.protocol == "grpc" else 2,
101
+ )
102
+ elif ocr_model_name in {"scene_text_ensemble", "scene_text_wrapper", "scene_text_python"}:
103
+ future_ocr_kwargs.update(
104
+ model_name=ocr_model_name,
105
+ input_names=["INPUT_IMAGE_URLS", "MERGE_LEVELS"],
106
+ output_names=["OUTPUT"],
107
+ dtypes=["BYTES", "BYTES"],
108
+ merge_level="word",
109
+ )
110
+ else:
111
+ raise ValueError(f"Unknown OCR model name: {ocr_model_name}")
112
+
113
+ with ThreadPoolExecutor(max_workers=2) as executor:
114
+ future_ocr = executor.submit(ocr_client.infer, **future_ocr_kwargs)
115
+ future_yolox = None
116
+ if enable_yolox:
117
+ future_yolox = executor.submit(yolox_client.infer, **future_yolox_kwargs)
118
+ if enable_yolox:
119
+ try:
120
+ yolox_results = future_yolox.result()
121
+ except Exception as e:
122
+ logger.error(f"Error calling yolox_client.infer: {e}", exc_info=True)
123
+ raise
124
+ else:
125
+ yolox_results = [None] * len(valid_images)
126
+
127
+ try:
128
+ ocr_results = future_ocr.result()
129
+ except Exception as e:
130
+ logger.error(f"Error calling ocr_client.infer: {e}", exc_info=True)
131
+ raise
132
+
133
+ return yolox_results, ocr_results
134
+
135
+
136
+ def _validate_inference_results(
137
+ yolox_results: Any,
138
+ ocr_results: Any,
139
+ valid_arrays: List[Any],
140
+ valid_images: List[str],
141
+ ) -> Tuple[List[Any], List[Any]]:
142
+ """
143
+ Validate that both inference results are lists and have the expected lengths.
144
+
145
+ If not, default values are assigned. Raises a ValueError if the lengths do not match.
146
+ """
147
+ if not isinstance(yolox_results, list) or not isinstance(ocr_results, list):
148
+ logger.warning(
149
+ "Unexpected result types from inference clients: yolox_results=%s, ocr_results=%s. "
150
+ "Proceeding with available results.",
151
+ type(yolox_results).__name__,
152
+ type(ocr_results).__name__,
153
+ )
154
+ if not isinstance(yolox_results, list):
155
+ yolox_results = [None] * len(valid_arrays)
156
+ if not isinstance(ocr_results, list):
157
+ ocr_results = [(None, None)] * len(valid_images)
158
+
159
+ if len(yolox_results) != len(valid_arrays):
160
+ raise ValueError(f"Expected {len(valid_arrays)} yolox results, got {len(yolox_results)}")
161
+ if len(ocr_results) != len(valid_images):
162
+ raise ValueError(f"Expected {len(valid_images)} ocr results, got {len(ocr_results)}")
163
+
164
+ return yolox_results, ocr_results
165
+
166
+
167
+ def _update_table_metadata(
168
+ base64_images: List[str],
169
+ yolox_client: Any,
170
+ ocr_client: Any,
171
+ ocr_model_name: str,
172
+ worker_pool_size: int = 8, # Not currently used
173
+ enable_yolox: bool = False,
174
+ trace_info: Optional[Dict] = None,
175
+ ) -> List[Tuple[str, Any, Any, Any]]:
176
+ """
177
+ Given a list of base64-encoded images, this function filters out images that do not meet
178
+ the minimum size requirements and then calls the OCR model via ocr_client.infer
179
+ to extract table data.
180
+
181
+ For each base64-encoded image, the result is a tuple:
182
+ (base64_image, yolox_result, ocr_text_predictions, ocr_bounding_boxes)
183
+
184
+ Images that do not meet the minimum size are skipped (resulting in placeholders).
185
+ The ocr_client is expected to handle any necessary batching and concurrency.
186
+ """
187
+ logger.debug(f"Running table extraction using protocol {ocr_client.protocol}")
188
+
189
+ # Initialize the results list with default placeholders.
190
+ results: List[Tuple[str, Any, Any, Any]] = [("", None, None, None)] * len(base64_images)
191
+
192
+ # Filter valid images based on size requirements.
193
+ valid_images, valid_arrays, valid_indices = _filter_valid_images(base64_images)
194
+
195
+ if not valid_images:
196
+ return results
197
+
198
+ # Run inference concurrently.
199
+ yolox_results, ocr_results = _run_inference(
200
+ enable_yolox=enable_yolox,
201
+ yolox_client=yolox_client,
202
+ ocr_client=ocr_client,
203
+ ocr_model_name=ocr_model_name,
204
+ valid_arrays=valid_arrays,
205
+ valid_images=valid_images,
206
+ trace_info=trace_info,
207
+ )
208
+
209
+ # Validate that the inference results have the expected structure.
210
+ yolox_results, ocr_results = _validate_inference_results(yolox_results, ocr_results, valid_arrays, valid_images)
211
+
212
+ # Combine results with the original order.
213
+ for idx, (yolox_res, ocr_res) in enumerate(zip(yolox_results, ocr_results)):
214
+ original_index = valid_indices[idx]
215
+ results[original_index] = (
216
+ base64_images[original_index],
217
+ yolox_res,
218
+ ocr_res[0],
219
+ ocr_res[1],
220
+ )
221
+
222
+ return results
223
+
224
+
225
+ def _create_yolox_client(
226
+ yolox_endpoints: Tuple[str, str],
227
+ yolox_protocol: str,
228
+ auth_token: str,
229
+ ) -> NimClient:
230
+ yolox_model_interface = YoloxTableStructureModelInterface()
231
+
232
+ yolox_client = create_inference_client(
233
+ endpoints=yolox_endpoints,
234
+ model_interface=yolox_model_interface,
235
+ auth_token=auth_token,
236
+ infer_protocol=yolox_protocol,
237
+ )
238
+
239
+ return yolox_client
240
+
241
+
242
+ def _create_ocr_client(
243
+ ocr_endpoints: Tuple[str, str],
244
+ ocr_protocol: str,
245
+ ocr_model_name: str,
246
+ auth_token: str,
247
+ ) -> NimClient:
248
+ ocr_model_interface = (
249
+ NemoRetrieverOCRModelInterface()
250
+ if ocr_model_name in {"scene_text_ensemble", "scene_text_wrapper", "scene_text_python"}
251
+ else PaddleOCRModelInterface()
252
+ )
253
+
254
+ ocr_client = create_inference_client(
255
+ endpoints=ocr_endpoints,
256
+ model_interface=ocr_model_interface,
257
+ auth_token=auth_token,
258
+ infer_protocol=ocr_protocol,
259
+ enable_dynamic_batching=(
260
+ True if ocr_model_name in {"scene_text_ensemble", "scene_text_wrapper", "scene_text_python"} else False
261
+ ),
262
+ dynamic_batch_memory_budget_mb=32,
263
+ )
264
+
265
+ return ocr_client
266
+
267
+
268
+ def extract_table_data_from_image_internal(
269
+ df_extraction_ledger: pd.DataFrame,
270
+ task_config: Union[IngestTaskTableExtraction, Dict[str, Any]],
271
+ extraction_config: TableExtractorSchema,
272
+ execution_trace_log: Optional[Dict] = None,
273
+ ) -> Tuple[pd.DataFrame, Dict]:
274
+ """
275
+ Extracts table data from a DataFrame in a bulk fashion rather than row-by-row,
276
+ following the chart extraction pattern.
277
+
278
+ Parameters
279
+ ----------
280
+ df_extraction_ledger : pd.DataFrame
281
+ DataFrame containing the content from which table data is to be extracted.
282
+ task_config : Dict[str, Any]
283
+ Dictionary containing task properties and configurations.
284
+ extraction_config : Any
285
+ The validated configuration object for table extraction.
286
+ execution_trace_log : Optional[Dict], optional
287
+ Optional trace information for debugging or logging. Defaults to None.
288
+
289
+ Returns
290
+ -------
291
+ Tuple[pd.DataFrame, Dict]
292
+ A tuple containing the updated DataFrame and the trace information.
293
+ """
294
+
295
+ _ = task_config # unused
296
+
297
+ if execution_trace_log is None:
298
+ execution_trace_log = {}
299
+ logger.debug("No trace_info provided. Initialized empty trace_info dictionary.")
300
+
301
+ if df_extraction_ledger.empty:
302
+ return df_extraction_ledger, execution_trace_log
303
+
304
+ endpoint_config = extraction_config.endpoint_config
305
+
306
+ # Get the grpc endpoint to determine the model if needed
307
+ ocr_grpc_endpoint = endpoint_config.ocr_endpoints[0]
308
+ ocr_model_name = get_ocr_model_name(ocr_grpc_endpoint)
309
+
310
+ try:
311
+ # 1) Identify rows that meet criteria (structured, subtype=table, table_metadata != None, content not empty)
312
+ def meets_criteria(row):
313
+ m = row.get("metadata", {})
314
+ if not m:
315
+ return False
316
+ content_md = m.get("content_metadata", {})
317
+ if (
318
+ content_md.get("type") == "structured"
319
+ and content_md.get("subtype") == "table"
320
+ and m.get("table_metadata") is not None
321
+ and m.get("content") not in [None, ""]
322
+ ):
323
+ return True
324
+ return False
325
+
326
+ mask = df_extraction_ledger.apply(meets_criteria, axis=1)
327
+ valid_indices = df_extraction_ledger[mask].index.tolist()
328
+
329
+ # If no rows meet the criteria, just return
330
+ if not valid_indices:
331
+ return df_extraction_ledger, {"trace_info": execution_trace_log}
332
+
333
+ # 2) Extract base64 images in the same order
334
+ base64_images = []
335
+ for idx in valid_indices:
336
+ meta = df_extraction_ledger.at[idx, "metadata"]
337
+ base64_images.append(meta["content"])
338
+
339
+ # 3) Call our bulk _update_metadata to get all results
340
+ table_content_format = (
341
+ df_extraction_ledger.at[valid_indices[0], "metadata"]["table_metadata"].get("table_content_format")
342
+ or TableFormatEnum.PSEUDO_MARKDOWN
343
+ )
344
+ enable_yolox = True if table_content_format in (TableFormatEnum.MARKDOWN,) else False
345
+
346
+ yolox_client = _create_yolox_client(
347
+ endpoint_config.yolox_endpoints,
348
+ endpoint_config.yolox_infer_protocol,
349
+ endpoint_config.auth_token,
350
+ )
351
+ ocr_client = _create_ocr_client(
352
+ endpoint_config.ocr_endpoints,
353
+ endpoint_config.ocr_infer_protocol,
354
+ ocr_model_name,
355
+ endpoint_config.auth_token,
356
+ )
357
+
358
+ bulk_results = _update_table_metadata(
359
+ base64_images=base64_images,
360
+ yolox_client=yolox_client,
361
+ ocr_client=ocr_client,
362
+ ocr_model_name=ocr_model_name,
363
+ worker_pool_size=endpoint_config.workers_per_progress_engine,
364
+ enable_yolox=enable_yolox,
365
+ trace_info=execution_trace_log,
366
+ )
367
+
368
+ # 4) Write the results (bounding_boxes, text_predictions) back
369
+ for row_id, idx in enumerate(valid_indices):
370
+ # unpack (base64_image, (yolox_predictions, ocr_bounding boxes, ocr_text_predictions))
371
+ _, cell_predictions, bounding_boxes, text_predictions = bulk_results[row_id]
372
+
373
+ if table_content_format == TableFormatEnum.SIMPLE:
374
+ table_content = " ".join(text_predictions)
375
+ elif table_content_format == TableFormatEnum.PSEUDO_MARKDOWN:
376
+ table_content = convert_ocr_response_to_psuedo_markdown(bounding_boxes, text_predictions)
377
+ elif table_content_format == TableFormatEnum.MARKDOWN:
378
+ table_content = join_yolox_table_structure_and_ocr_output(
379
+ cell_predictions, bounding_boxes, text_predictions
380
+ )
381
+ else:
382
+ raise ValueError(f"Unexpected table format: {table_content_format}")
383
+
384
+ df_extraction_ledger.at[idx, "metadata"]["table_metadata"]["table_content"] = table_content
385
+ df_extraction_ledger.at[idx, "metadata"]["table_metadata"]["table_content_format"] = table_content_format
386
+
387
+ return df_extraction_ledger, {"trace_info": execution_trace_log}
388
+
389
+ except Exception:
390
+ logger.exception("Error occurred while extracting table data.", exc_info=True)
391
+ raise
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024-25, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,19 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .adobe import adobe_extractor
6
+ from .llama import llama_parse_extractor
7
+ from .nemotron_parse import nemotron_parse_extractor
8
+ from .pdfium import pdfium_extractor
9
+ from .tika import tika_extractor
10
+ from .unstructured_io import unstructured_io_extractor
11
+
12
+ __all__ = [
13
+ "adobe_extractor",
14
+ "llama_parse_extractor",
15
+ "nemotron_parse_extractor",
16
+ "pdfium_extractor",
17
+ "tika_extractor",
18
+ "unstructured_io_extractor",
19
+ ]