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,428 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from typing import List, Any
7
+ from typing import Optional
8
+ from typing import Tuple
9
+
10
+ import numpy as np
11
+ import pypdfium2 as pdfium
12
+ import pypdfium2.raw as pdfium_c
13
+ from numpy import dtype
14
+ from numpy import ndarray
15
+
16
+ from nv_ingest_api.internal.primitives.tracing.tagging import traceable_func
17
+ from nv_ingest_api.util.image_processing.clustering import (
18
+ group_bounding_boxes,
19
+ combine_groups_into_bboxes,
20
+ remove_superset_bboxes,
21
+ )
22
+ from nv_ingest_api.util.image_processing.transforms import pad_image, numpy_to_base64, crop_image, scale_numpy_image
23
+ from nv_ingest_api.util.metadata.aggregators import Base64Image
24
+ from nv_ingest_api.internal.primitives.nim.model_interface.yolox import YOLOX_PAGE_IMAGE_FORMAT
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ PDFIUM_PAGEOBJ_MAPPING = {
29
+ pdfium_c.FPDF_PAGEOBJ_TEXT: "TEXT",
30
+ pdfium_c.FPDF_PAGEOBJ_PATH: "PATH",
31
+ pdfium_c.FPDF_PAGEOBJ_IMAGE: "IMAGE",
32
+ pdfium_c.FPDF_PAGEOBJ_SHADING: "SHADING",
33
+ pdfium_c.FPDF_PAGEOBJ_FORM: "FORM",
34
+ }
35
+
36
+
37
+ def convert_bitmap_to_corrected_numpy(bitmap: pdfium.PdfBitmap) -> np.ndarray:
38
+ """
39
+ Converts a PdfBitmap to a correctly formatted NumPy array, handling any necessary
40
+ channel swapping based on the bitmap's mode.
41
+
42
+ Parameters
43
+ ----------
44
+ bitmap : pdfium.PdfBitmap
45
+ The bitmap object rendered from a PDF page.
46
+
47
+ Returns
48
+ -------
49
+ np.ndarray
50
+ A NumPy array representing the correctly formatted image data.
51
+ """
52
+ mode = bitmap.mode # Use the mode to identify the correct format
53
+
54
+ # Convert to a NumPy array using the built-in method
55
+ img_arr = bitmap.to_numpy().copy()
56
+
57
+ # Automatically handle channel swapping if necessary
58
+ if mode in {"BGRA", "BGRX"}:
59
+ img_arr = img_arr[..., [2, 1, 0, 3]] # Swap BGR(A) to RGB(A)
60
+ elif mode == "BGR":
61
+ img_arr = img_arr[..., [2, 1, 0]] # Swap BGR to RGB
62
+
63
+ return img_arr
64
+
65
+
66
+ def pdfium_try_get_bitmap_as_numpy(image_obj) -> np.ndarray:
67
+ """
68
+ Attempts to retrieve the bitmap from a PdfImage object and convert it to a NumPy array,
69
+ first with rendering enabled and then without rendering if the first attempt fails.
70
+
71
+ Parameters
72
+ ----------
73
+ image_obj : PdfImage
74
+ The PdfImage object from which to extract the bitmap.
75
+
76
+ Returns
77
+ -------
78
+ np.ndarray
79
+ The extracted bitmap as a NumPy array.
80
+
81
+ Raises
82
+ ------
83
+ PdfiumError
84
+ If an exception occurs during bitmap retrieval and both attempts fail.
85
+
86
+ Notes
87
+ -----
88
+ This function first tries to retrieve the bitmap with rendering enabled (`render=True`).
89
+ If that fails or the bitmap returned is `None`, it attempts to retrieve the raw bitmap
90
+ without rendering (`render=False`).
91
+ Any errors encountered during these attempts are logged at the debug level.
92
+ """
93
+ image_bitmap = None
94
+
95
+ # First attempt with rendering enabled
96
+ try:
97
+ # logger.debug("Attempting to get rendered bitmap.")
98
+ image_bitmap = image_obj.get_bitmap(render=True)
99
+ except pdfium.PdfiumError as e:
100
+ logger.debug(f"Failed to get rendered bitmap: {e}")
101
+
102
+ # If rendering failed or returned None, try without rendering
103
+ if image_bitmap is None:
104
+ try:
105
+ # logger.debug("Attempting to get raw bitmap without rendering.")
106
+ image_bitmap = image_obj.get_bitmap(render=False)
107
+ except pdfium.PdfiumError as e:
108
+ logger.debug(f"Failed to get raw bitmap: {e}")
109
+ raise # Re-raise the exception to ensure the failure is handled upstream
110
+
111
+ # Final check if bitmap is still None
112
+ if image_bitmap is None:
113
+ logger.debug("Failed to obtain bitmap from the image object after both attempts.")
114
+ raise ValueError("Failed to retrieve bitmap from the PdfImage object.")
115
+
116
+ # Convert the bitmap to a NumPy array
117
+ img_array = convert_bitmap_to_corrected_numpy(image_bitmap)
118
+
119
+ return img_array
120
+
121
+
122
+ @traceable_func(trace_name="pdf_extraction::pdfium_pages_to_numpy")
123
+ def pdfium_pages_to_numpy(
124
+ pages: List[pdfium.PdfPage],
125
+ render_dpi: int = 300,
126
+ scale_tuple: Optional[Tuple[int, int]] = None,
127
+ padding_tuple: Optional[Tuple[int, int]] = None,
128
+ rotation: int = 0,
129
+ ) -> tuple[list[ndarray | ndarray[Any, dtype[Any]]], list[tuple[int, int]]]:
130
+ """
131
+ Converts a list of PdfPage objects to a list of NumPy arrays, where each array
132
+ represents an image of the corresponding PDF page.
133
+
134
+ The function renders each page as a bitmap, converts it to a PIL image, applies any
135
+ specified scaling using the thumbnail approach, and adds padding if requested. The
136
+ DPI for rendering can be specified, with a default value of 300 DPI.
137
+
138
+ Parameters
139
+ ----------
140
+ pages : List[pdfium.PdfPage]
141
+ A list of PdfPage objects to be rendered and converted into NumPy arrays.
142
+ render_dpi : int, optional
143
+ The DPI (dots per inch) at which to render the pages. Must be between 50 and 1200.
144
+ Defaults to 300.
145
+ scale_tuple : Optional[Tuple[int, int]], optional
146
+ A tuple (width, height) to resize the rendered image to using the thumbnail approach.
147
+ Defaults to None.
148
+ padding_tuple : Optional[Tuple[int, int]], optional
149
+ A tuple (width, height) to pad the image to. Defaults to None.
150
+ rotation:
151
+
152
+ Returns
153
+ -------
154
+ tuple
155
+ A tuple containing:
156
+ - A list of NumPy arrays, where each array corresponds to an image of a PDF page.
157
+ Each array is an independent copy of the rendered image data.
158
+ - A list of padding offsets applied to each image, as tuples of (offset_width, offset_height).
159
+
160
+ Raises
161
+ ------
162
+ ValueError
163
+ If the render_dpi is outside the allowed range (50-1200).
164
+ PdfiumError
165
+ If there is an issue rendering the page or converting it to a NumPy array.
166
+ IOError
167
+ If there is an error saving the image to disk.
168
+ """
169
+ if not (50 <= render_dpi <= 1200):
170
+ raise ValueError("render_dpi must be between 50 and 1200.")
171
+
172
+ images = []
173
+ padding_offsets = []
174
+ scale = render_dpi / 72 # 72 DPI is the base DPI in PDFium
175
+
176
+ for idx, page in enumerate(pages):
177
+ # Render the page as a bitmap with the specified scale and rotation
178
+ page_bitmap = page.render(scale=scale, rotation=rotation)
179
+ img_arr = convert_bitmap_to_corrected_numpy(page_bitmap)
180
+ # Apply scaling using the thumbnail approach if specified
181
+ if scale_tuple:
182
+ img_arr = scale_numpy_image(img_arr, scale_tuple)
183
+ # Apply padding if specified
184
+ if padding_tuple:
185
+ img_arr, (pad_width, pad_height) = pad_image(
186
+ img_arr, target_width=padding_tuple[0], target_height=padding_tuple[1]
187
+ )
188
+ padding_offsets.append((pad_width, pad_height))
189
+ else:
190
+ padding_offsets.append((0, 0))
191
+
192
+ images.append(img_arr)
193
+
194
+ return images, padding_offsets
195
+
196
+
197
+ def convert_pdfium_position(pos, page_width, page_height):
198
+ """
199
+ Convert a PDFium bounding box (which typically has an origin at the bottom-left)
200
+ to a more standard bounding-box format with y=0 at the top.
201
+
202
+ Note:
203
+ This method assumes the PDF coordinate system follows the common convention
204
+ where the origin is at the bottom-left. However, per the PDF specification,
205
+ the coordinate system can theoretically be defined between any opposite corners,
206
+ and its origin may not necessarily be (0,0). This implementation may not handle
207
+ all edge cases where the coordinate system is arbitrarily transformed.
208
+
209
+ Further processing may be necessary downstream, particularly in filtering or
210
+ deduplication stages, to account for variations in coordinate transformations
211
+ and ensure consistent bounding-box comparisons.
212
+
213
+ See https://github.com/pypdfium2-team/pypdfium2/discussions/284.
214
+ """
215
+ left, bottom, right, top = pos
216
+ x0, x1 = left, right
217
+ y0, y1 = page_height - top, page_height - bottom
218
+
219
+ x0 = max(0, x0)
220
+ y0 = max(0, y0)
221
+ x1 = min(page_width, x1)
222
+ y1 = min(page_height, y1)
223
+
224
+ return [int(x0), int(y0), int(x1), int(y1)]
225
+
226
+
227
+ def extract_simple_images_from_pdfium_page(page, max_depth):
228
+ page_width = page.get_width()
229
+ page_height = page.get_height()
230
+
231
+ try:
232
+ image_objects = page.get_objects(
233
+ filter=(pdfium_c.FPDF_PAGEOBJ_IMAGE,),
234
+ max_depth=max_depth,
235
+ )
236
+ except Exception as e:
237
+ logger.exception(f"Unhandled error extracting image: {e}")
238
+ return []
239
+
240
+ extracted_images = []
241
+ for obj in image_objects:
242
+ try:
243
+ # Attempt to retrieve the image bitmap
244
+ image_numpy: np.ndarray = pdfium_try_get_bitmap_as_numpy(obj) # noqa
245
+ image_base64: str = numpy_to_base64(image_numpy, format=YOLOX_PAGE_IMAGE_FORMAT)
246
+ image_bbox = obj.get_pos()
247
+ image_size = obj.get_size()
248
+ if image_size[0] < 10 and image_size[1] < 10:
249
+ continue
250
+
251
+ image_data = Base64Image(
252
+ image=image_base64,
253
+ bbox=image_bbox,
254
+ width=image_size[0],
255
+ height=image_size[1],
256
+ max_width=page_width,
257
+ max_height=page_height,
258
+ )
259
+ extracted_images.append(image_data)
260
+ except Exception as e:
261
+ logger.exception(f"Unhandled error extracting image: {e}")
262
+ pass # Pdfium failed to extract the image associated with this object - corrupt or missing.
263
+
264
+ return extracted_images
265
+
266
+
267
+ def extract_nested_simple_images_from_pdfium_page(page):
268
+ return extract_simple_images_from_pdfium_page(page, max_depth=2)
269
+
270
+
271
+ def extract_top_level_simple_images_from_pdfium_page(page):
272
+ return extract_simple_images_from_pdfium_page(page, max_depth=1)
273
+
274
+
275
+ def extract_merged_images_from_pdfium_page(page, merge=True, **kwargs):
276
+ """
277
+ Extract bounding boxes of image objects from a PDFium page, with optional merging
278
+ of bounding boxes that likely belong to the same compound image.
279
+ """
280
+ threshold = kwargs.get("images_threshold", 10.0)
281
+ max_num_boxes = kwargs.get("images_max_num_boxes", 1_024)
282
+
283
+ page_width = page.get_width()
284
+ page_height = page.get_height()
285
+
286
+ image_bboxes = []
287
+ for obj in page.get_objects(
288
+ filter=(pdfium_c.FPDF_PAGEOBJ_IMAGE,),
289
+ max_depth=1,
290
+ ):
291
+ image_bbox = convert_pdfium_position(obj.get_pos(), page_width, page_height)
292
+ image_bboxes.append(image_bbox)
293
+
294
+ # If no merging is requested or no bounding boxes exist, return the list as is
295
+ if (not merge) or (not image_bboxes):
296
+ return image_bboxes
297
+
298
+ merged_groups = group_bounding_boxes(image_bboxes, threshold=threshold, max_num_boxes=max_num_boxes)
299
+ merged_bboxes = combine_groups_into_bboxes(image_bboxes, merged_groups)
300
+
301
+ return merged_bboxes
302
+
303
+
304
+ def extract_merged_shapes_from_pdfium_page(page, merge=True, **kwargs):
305
+ """
306
+ Extract bounding boxes of path objects (shapes) from a PDFium page, and optionally merge
307
+ those bounding boxes if they appear to be part of the same shape group. Also filters out
308
+ shapes that occupy more than half the page area.
309
+ """
310
+ threshold = kwargs.get("shapes_threshold", 10.0)
311
+ max_num_boxes = kwargs.get("shapes_max_num_boxes", 2_048)
312
+ min_num_components = kwargs.get("shapes_min_num_components", 3)
313
+
314
+ page_width = page.get_width()
315
+ page_height = page.get_height()
316
+ page_area = page_width * page_height
317
+
318
+ path_bboxes = []
319
+ for obj in page.get_objects(
320
+ filter=(pdfium_c.FPDF_PAGEOBJ_PATH,),
321
+ max_depth=1,
322
+ ):
323
+ path_bbox = convert_pdfium_position(obj.get_pos(), page_width, page_height)
324
+ path_bboxes.append(path_bbox)
325
+
326
+ # If merging is disabled or no bounding boxes were found, return them as-is
327
+ if (not merge) or (not path_bboxes):
328
+ return path_bboxes
329
+
330
+ merged_bboxes = []
331
+
332
+ path_groups = group_bounding_boxes(path_bboxes, threshold=threshold, max_num_boxes=max_num_boxes)
333
+ path_bboxes = combine_groups_into_bboxes(path_bboxes, path_groups, min_num_components=min_num_components)
334
+ for bbox in path_bboxes:
335
+ bbox_area = abs(bbox[0] - bbox[2]) * abs(bbox[1] - bbox[3])
336
+ # Exclude shapes that are too large (likely page backgrounds or false positives)
337
+ if bbox_area > 0.5 * page_area:
338
+ continue
339
+ merged_bboxes.append(bbox)
340
+
341
+ return merged_bboxes
342
+
343
+
344
+ def extract_forms_from_pdfium_page(page, **kwargs):
345
+ """
346
+ Extract bounding boxes for PDF form objects from a PDFium page, removing any
347
+ bounding boxes that strictly enclose other boxes (i.e., are strict supersets).
348
+ """
349
+ threshold = kwargs.get("forms_threshold", 10.0)
350
+ max_num_boxes = kwargs.get("forms_max_num_boxes", 1_024)
351
+
352
+ page_width = page.get_width()
353
+ page_height = page.get_height()
354
+ page_area = page_width * page_height
355
+
356
+ form_bboxes = []
357
+ for obj in page.get_objects(
358
+ filter=(pdfium_c.FPDF_PAGEOBJ_FORM,),
359
+ max_depth=1,
360
+ ):
361
+ form_bbox = convert_pdfium_position(obj.get_pos(), page_width, page_height)
362
+ form_bboxes.append(form_bbox)
363
+
364
+ merged_bboxes = []
365
+ form_groups = group_bounding_boxes(form_bboxes, threshold=threshold, max_num_boxes=max_num_boxes)
366
+ form_bboxes = combine_groups_into_bboxes(form_bboxes, form_groups)
367
+ for bbox in form_bboxes:
368
+ bbox_area = abs(bbox[0] - bbox[2]) * abs(bbox[1] - bbox[3])
369
+ # Exclude shapes that are too large (likely page backgrounds or false positives)
370
+ if bbox_area > 0.5 * page_area:
371
+ continue
372
+ merged_bboxes.append(bbox)
373
+
374
+ # Remove any bounding box that strictly encloses another.
375
+ # The larger one is likely a background.
376
+ results = remove_superset_bboxes(merged_bboxes)
377
+
378
+ return results
379
+
380
+
381
+ def extract_image_like_objects_from_pdfium_page(page, merge=True, **kwargs):
382
+ page_width = page.get_width()
383
+ page_height = page.get_height()
384
+ rotation = page.get_rotation()
385
+
386
+ try:
387
+ original_images, _ = pdfium_pages_to_numpy(
388
+ [page], # A batch with a single image.
389
+ render_dpi=72, # dpi = 72 is equivalent to scale = 1.
390
+ rotation=rotation, # Without rotation, coordinates from page.get_pos() will not match.
391
+ )
392
+ image_bboxes = extract_merged_images_from_pdfium_page(page, merge=merge, **kwargs)
393
+ shape_bboxes = extract_merged_shapes_from_pdfium_page(page, merge=merge, **kwargs)
394
+ form_bboxes = extract_forms_from_pdfium_page(page, **kwargs)
395
+ except Exception as e:
396
+ logger.exception(f"Unhandled error extracting image: {e}")
397
+ return []
398
+
399
+ extracted_images = []
400
+ for bbox in image_bboxes + shape_bboxes + form_bboxes:
401
+ try:
402
+ cropped_image = crop_image(original_images[0], bbox, min_width=10, min_height=10)
403
+ if cropped_image is None: # Small images are filtered out.
404
+ continue
405
+ image_base64 = numpy_to_base64(cropped_image)
406
+ image_data = Base64Image(
407
+ image=image_base64,
408
+ bbox=bbox,
409
+ width=bbox[2] - bbox[0],
410
+ height=bbox[3] - bbox[1],
411
+ max_width=page_width,
412
+ max_height=page_height,
413
+ )
414
+ extracted_images.append(image_data)
415
+ except Exception as e:
416
+ logger.exception(f"Unhandled error extracting image: {e}")
417
+ pass # Pdfium failed to extract the image associated with this object - corrupt or missing.
418
+
419
+ return extracted_images
420
+
421
+
422
+ def is_scanned_page(page) -> bool:
423
+ tp = page.get_textpage()
424
+ text = tp.get_text_bounded() or ""
425
+ num_chars = len(text.strip())
426
+ num_images = sum(1 for obj in page.get_objects() if obj.type == pdfium_c.FPDF_PAGEOBJ_IMAGE)
427
+
428
+ return num_chars == 0 and num_images > 0
@@ -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,10 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from nv_ingest_api.util.exception_handlers.schemas import schema_exception_handler
6
+
7
+
8
+ @schema_exception_handler
9
+ def validate_schema(metadata, Schema):
10
+ return Schema(**metadata)
@@ -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,86 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from abc import ABC
6
+ from abc import abstractmethod
7
+ from enum import Enum, auto
8
+ from typing import Tuple
9
+
10
+ from nv_ingest_api.internal.schemas.message_brokers.response_schema import ResponseSchema
11
+
12
+
13
+ class FetchMode(Enum):
14
+ DESTRUCTIVE = auto() # Read and delete immediately (current behavior)
15
+ NON_DESTRUCTIVE = auto() # Read without deleting (requires TTL on Redis data)
16
+ CACHE_BEFORE_DELETE = auto() # Read, write to local cache, then delete from Redis
17
+
18
+
19
+ class MessageBrokerClientBase(ABC):
20
+ """
21
+ Abstract base class for a messaging client to interface with various messaging systems.
22
+
23
+ Provides a standard interface for sending and receiving messages with connection management
24
+ and retry logic.
25
+ """
26
+
27
+ @abstractmethod
28
+ def __init__(
29
+ self,
30
+ host: str,
31
+ port: int,
32
+ db: int = 0,
33
+ max_retries: int = 0,
34
+ max_backoff: int = 32,
35
+ connection_timeout: int = 300,
36
+ max_pool_size: int = 128,
37
+ use_ssl: bool = False,
38
+ ):
39
+ """
40
+ Initialize the messaging client with connection parameters.
41
+ """
42
+
43
+ @abstractmethod
44
+ def get_client(self):
45
+ """
46
+ Returns the client instance, reconnecting if necessary.
47
+
48
+ Returns:
49
+ The client instance.
50
+ """
51
+
52
+ @abstractmethod
53
+ def ping(self) -> bool:
54
+ """
55
+ Checks if the server is responsive.
56
+
57
+ Returns:
58
+ True if the server responds to a ping, False otherwise.
59
+ """
60
+
61
+ @abstractmethod
62
+ def fetch_message(
63
+ self, job_index: str, timeout: Tuple[int, float] = (100, None), override_fetch_mode: FetchMode = None
64
+ ) -> ResponseSchema:
65
+ """
66
+ Fetches a message from the specified queue with retries on failure.
67
+
68
+ Parameters:
69
+ job_index (str): The index of the job to fetch the message for.
70
+ timeout (float): The timeout in seconds for blocking until a message is available.
71
+ override_fetch_mode: Optional; overrides the default fetch mode.
72
+
73
+ Returns:
74
+ The fetched message, or None if no message could be fetched.
75
+ """
76
+
77
+ @abstractmethod
78
+ def submit_message(self, channel_name: str, message: str, for_nv_ingest=False) -> ResponseSchema:
79
+ """
80
+ Submits a message to a specified queue with retries on failure.
81
+
82
+ Parameters:
83
+ channel_name (str): The name of the queue to submit the message to.
84
+ message (str): The message to submit.
85
+ for_nv_ingest (bool): Whether the message is for NV Ingest.
86
+ """
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES.
2
+ # All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -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