code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def pop(self, transaction_id):
"""Pop a message from the queue and mark it as in-flight."""
with self.lock:
while not self.queue:
self.not_empty.wait()
index, message = heapq.heappop(self.queue)
self.in_flight[transaction_id] = (index, message)
... | Pop a message from the queue and mark it as in-flight. | pop | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | Apache-2.0 |
def acknowledge(self, transaction_id):
"""Acknowledge that a message has been processed."""
with self.lock:
if transaction_id in self.in_flight:
del self.in_flight[transaction_id] | Acknowledge that a message has been processed. | acknowledge | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | Apache-2.0 |
def return_message(self, transaction_id):
"""Return an unacknowledged message back to the queue."""
with self.lock:
if transaction_id in self.in_flight:
index, message = self.in_flight.pop(transaction_id)
heapq.heappush(self.queue, (index, message))
... | Return an unacknowledged message back to the queue. | return_message | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | Apache-2.0 |
def empty(self):
"""Check if the queue is empty."""
with self.lock:
return not self.queue | Check if the queue is empty. | empty | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | Apache-2.0 |
def full(self):
"""Check if the queue is full."""
with self.lock:
return self.maxsize > 0 and (len(self.queue) + len(self.in_flight)) >= self.maxsize | Check if the queue is full. | full | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/ordered_message_queue.py | Apache-2.0 |
def __init__(
self,
host: str,
port: int,
db: int = 0,
max_retries: int = 3,
max_backoff: int = 32,
connection_timeout: int = 300,
max_pool_size: int = 128,
use_ssl: bool = False,
):
"""
Initialize the SimpleClient with configur... |
Initialize the SimpleClient with configuration parameters.
Parameters
----------
host : str
The hostname or IP address of the broker.
port : int
The port number of the broker.
db : int, optional
The database index (default: 0).
... | __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def fetch_message(
self,
queue_name: str,
timeout: Optional[Tuple[int, Union[float]]] = (100, None),
override_fetch_mode: FetchMode = None,
) -> ResponseSchema:
"""
Fetch a message from the specified queue.
Parameters
----------
queue_name : s... |
Fetch a message from the specified queue.
Parameters
----------
queue_name : str
The name of the queue.
timeout : float, optional
Timeout in seconds for the operation.
Returns
-------
ResponseSchema
The response conta... | fetch_message | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def _handle_push(
self, queue_name: str, message: str, timeout: Optional[Tuple[int, Union[float, None]]], for_nv_ingest: bool
) -> ResponseSchema:
"""
Push a message to the queue with optional timeout.
Parameters
----------
queue_name : str
The name of th... |
Push a message to the queue with optional timeout.
Parameters
----------
queue_name : str
The name of the queue.
message : str
The message to push.
timeout : float, optional
Timeout in seconds for the operation.
for_nv_ingest ... | _handle_push | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def _handle_pop(self, queue_name: str, timeout: Optional[Tuple[int, Union[float, None]]]) -> ResponseSchema:
"""
Pop a message from the queue with optional timeout.
Parameters
----------
queue_name : str
The name of the queue.
timeout : float, optional
... |
Pop a message from the queue with optional timeout.
Parameters
----------
queue_name : str
The name of the queue.
timeout : float, optional
Timeout in seconds for the operation.
Returns
-------
ResponseSchema
The resp... | _handle_pop | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def _execute_simple_command(self, command: dict) -> ResponseSchema:
"""
Execute a simple command on the broker and process the response.
Parameters
----------
command : dict
The command to execute.
Returns
-------
ResponseSchema
T... |
Execute a simple command on the broker and process the response.
Parameters
----------
command : dict
The command to execute.
Returns
-------
ResponseSchema
The response from the broker.
| _execute_simple_command | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def _send(self, sock: socket.socket, data: bytes) -> None:
"""
Send data over a socket connection with a length header.
Parameters
----------
sock : socket.socket
The socket connection.
data : bytes
The data to send.
Raises
------... |
Send data over a socket connection with a length header.
Parameters
----------
sock : socket.socket
The socket connection.
data : bytes
The data to send.
Raises
------
ConnectionError
If sending data fails.
| _send | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def _recv(self, sock: socket.socket) -> str:
"""
Receive data from a socket connection based on a length header.
Parameters
----------
sock : socket.socket
The socket connection.
Returns
-------
str
The received data as a string.
... |
Receive data from a socket connection based on a length header.
Parameters
----------
sock : socket.socket
The socket connection.
Returns
-------
str
The received data as a string.
Raises
------
ConnectionError
... | _recv | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def _recv_exact(self, sock: socket.socket, num_bytes: int) -> Optional[bytes]:
"""
Receive an exact number of bytes from a socket connection.
Parameters
----------
sock : socket.socket
The socket connection.
num_bytes : int
The number of bytes to ... |
Receive an exact number of bytes from a socket connection.
Parameters
----------
sock : socket.socket
The socket connection.
num_bytes : int
The number of bytes to receive.
Returns
-------
Optional[bytes]
The received... | _recv_exact | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/simple_client.py | Apache-2.0 |
def extract_pdf_metadata(doc: pdfium.PdfDocument, source_id: str) -> PDFMetadata:
"""
Extracts metadata and relevant information from a PDF document.
Parameters
----------
pdf_stream : bytes
The PDF document data as a byte stream.
source_id : str
The identifier for the source do... |
Extracts metadata and relevant information from a PDF document.
Parameters
----------
pdf_stream : bytes
The PDF document data as a byte stream.
source_id : str
The identifier for the source document, typically the filename.
Returns
-------
PDFMetadata
An objec... | extract_pdf_metadata | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/metadata/aggregators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/metadata/aggregators.py | Apache-2.0 |
def construct_image_metadata_from_base64(
base64_image: str,
page_idx: int,
page_count: int,
source_metadata: Dict[str, Any],
base_unified_metadata: Dict[str, Any],
) -> List[Any]:
"""
Extracts image data from a base64-encoded image string, decodes the image to get
its dimensions and bou... |
Extracts image data from a base64-encoded image string, decodes the image to get
its dimensions and bounding box, and constructs metadata for the image.
Parameters
----------
base64_image : str
A base64-encoded string representing the image.
page_idx : int
The index of the curr... | construct_image_metadata_from_base64 | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/metadata/aggregators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/metadata/aggregators.py | Apache-2.0 |
def construct_image_metadata_from_pdf_image(
pdf_image: PdfImage,
page_idx: int,
page_count: int,
source_metadata: Dict[str, Any],
base_unified_metadata: Dict[str, Any],
) -> List[Any]:
"""
Extracts image data from a PdfImage object, converts it to a base64-encoded string,
and constructs... |
Extracts image data from a PdfImage object, converts it to a base64-encoded string,
and constructs metadata for the image.
Parameters
----------
image_obj : PdfImage
The PdfImage object from which the image will be extracted.
page_idx : int
The index of the current page being p... | construct_image_metadata_from_pdf_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/metadata/aggregators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/metadata/aggregators.py | Apache-2.0 |
def construct_page_element_metadata(
structured_image: CroppedImageWithContent,
page_idx: int,
page_count: int,
source_metadata: Dict,
base_unified_metadata: Dict,
):
"""
+--------------------------------+--------------------------+------------+---+
| Table/Chart Metadata | ... |
+--------------------------------+--------------------------+------------+---+
| Table/Chart Metadata | | Extracted | Y |
| (tables within documents) | | | |
+--------------------------------+--------------------------+-----... | construct_page_element_metadata | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/metadata/aggregators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/metadata/aggregators.py | Apache-2.0 |
def result(self) -> Any:
"""
Retrieve the result from the future, blocking until it is available.
Returns
-------
Any
The result returned by the worker function.
Raises
------
Exception
If the worker function raised an exception, ... |
Retrieve the result from the future, blocking until it is available.
Returns
-------
Any
The result returned by the worker function.
Raises
------
Exception
If the worker function raised an exception, it is re-raised here.
| result | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | Apache-2.0 |
def __new__(cls) -> "ProcessWorkerPoolSingleton":
"""
Create or return the singleton instance of ProcessWorkerPoolSingleton.
Returns
-------
ProcessWorkerPoolSingleton
The singleton instance.
"""
logger.debug("Creating ProcessWorkerPoolSingleton insta... |
Create or return the singleton instance of ProcessWorkerPoolSingleton.
Returns
-------
ProcessWorkerPoolSingleton
The singleton instance.
| __new__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | Apache-2.0 |
def _initialize(self, total_max_workers: int) -> None:
"""
Initialize the worker pool with the specified number of worker processes.
Parameters
----------
total_max_workers : int
The total number of worker processes to start.
"""
self._total_workers =... |
Initialize the worker pool with the specified number of worker processes.
Parameters
----------
total_max_workers : int
The total number of worker processes to start.
| _initialize | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | Apache-2.0 |
def _worker(task_queue: mp.Queue) -> None:
"""
Worker process that continuously processes tasks from the task queue.
Parameters
----------
task_queue : mp.Queue
The queue from which tasks are retrieved.
"""
logger.debug("Worker process started: PID %d... |
Worker process that continuously processes tasks from the task queue.
Parameters
----------
task_queue : mp.Queue
The queue from which tasks are retrieved.
| _worker | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | Apache-2.0 |
def close(self) -> None:
"""
Closes the worker pool and terminates all worker processes.
Sends a stop signal to each worker and waits for them to terminate.
"""
logger.debug("Closing ProcessWorkerPoolSingleton...")
# Send a stop signal (None) for each worker.
for... |
Closes the worker pool and terminates all worker processes.
Sends a stop signal to each worker and waits for them to terminate.
| close | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/multi_processing/mp_pool_singleton.py | Apache-2.0 |
def create_inference_client(
endpoints: Tuple[str, str],
model_interface: ModelInterface,
auth_token: Optional[str] = None,
infer_protocol: Optional[str] = None,
timeout: float = 120.0,
max_retries: int = 5,
) -> NimClient:
"""
Create a NimClient for interfacing with a model inference se... |
Create a NimClient for interfacing with a model inference server.
Parameters
----------
endpoints : tuple
A tuple containing the gRPC and HTTP endpoints.
model_interface : ModelInterface
The model interface implementation to use.
auth_token : str, optional
Authorization... | create_inference_client | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/nim/__init__.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/nim/__init__.py | Apache-2.0 |
def convert_bitmap_to_corrected_numpy(bitmap: pdfium.PdfBitmap) -> np.ndarray:
"""
Converts a PdfBitmap to a correctly formatted NumPy array, handling any necessary
channel swapping based on the bitmap's mode.
Parameters
----------
bitmap : pdfium.PdfBitmap
The bitmap object rendered fr... |
Converts a PdfBitmap to a correctly formatted NumPy array, handling any necessary
channel swapping based on the bitmap's mode.
Parameters
----------
bitmap : pdfium.PdfBitmap
The bitmap object rendered from a PDF page.
Returns
-------
np.ndarray
A NumPy array represent... | convert_bitmap_to_corrected_numpy | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def pdfium_try_get_bitmap_as_numpy(image_obj) -> np.ndarray:
"""
Attempts to retrieve the bitmap from a PdfImage object and convert it to a NumPy array,
first with rendering enabled and then without rendering if the first attempt fails.
Parameters
----------
image_obj : PdfImage
The Pdf... |
Attempts to retrieve the bitmap from a PdfImage object and convert it to a NumPy array,
first with rendering enabled and then without rendering if the first attempt fails.
Parameters
----------
image_obj : PdfImage
The PdfImage object from which to extract the bitmap.
Returns
----... | pdfium_try_get_bitmap_as_numpy | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def pdfium_pages_to_numpy(
pages: List[pdfium.PdfPage],
render_dpi: int = 300,
scale_tuple: Optional[Tuple[int, int]] = None,
padding_tuple: Optional[Tuple[int, int]] = None,
rotation: int = 0,
) -> tuple[list[ndarray | ndarray[Any, dtype[Any]]], list[tuple[int, int]]]:
"""
Converts a list o... |
Converts a list of PdfPage objects to a list of NumPy arrays, where each array
represents an image of the corresponding PDF page.
The function renders each page as a bitmap, converts it to a PIL image, applies any
specified scaling using the thumbnail approach, and adds padding if requested. The
D... | pdfium_pages_to_numpy | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def convert_pdfium_position(pos, page_width, page_height):
"""
Convert a PDFium bounding box (which typically has an origin at the bottom-left)
to a more standard bounding-box format with y=0 at the top.
Note:
This method assumes the PDF coordinate system follows the common convention
w... |
Convert a PDFium bounding box (which typically has an origin at the bottom-left)
to a more standard bounding-box format with y=0 at the top.
Note:
This method assumes the PDF coordinate system follows the common convention
where the origin is at the bottom-left. However, per the PDF specif... | convert_pdfium_position | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def extract_merged_images_from_pdfium_page(page, merge=True, **kwargs):
"""
Extract bounding boxes of image objects from a PDFium page, with optional merging
of bounding boxes that likely belong to the same compound image.
"""
threshold = kwargs.get("images_threshold", 10.0)
max_num_boxes = kwar... |
Extract bounding boxes of image objects from a PDFium page, with optional merging
of bounding boxes that likely belong to the same compound image.
| extract_merged_images_from_pdfium_page | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def extract_merged_shapes_from_pdfium_page(page, merge=True, **kwargs):
"""
Extract bounding boxes of path objects (shapes) from a PDFium page, and optionally merge
those bounding boxes if they appear to be part of the same shape group. Also filters out
shapes that occupy more than half the page area.
... |
Extract bounding boxes of path objects (shapes) from a PDFium page, and optionally merge
those bounding boxes if they appear to be part of the same shape group. Also filters out
shapes that occupy more than half the page area.
| extract_merged_shapes_from_pdfium_page | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def extract_forms_from_pdfium_page(page, **kwargs):
"""
Extract bounding boxes for PDF form objects from a PDFium page, removing any
bounding boxes that strictly enclose other boxes (i.e., are strict supersets).
"""
threshold = kwargs.get("forms_threshold", 10.0)
max_num_boxes = kwargs.get("form... |
Extract bounding boxes for PDF form objects from a PDFium page, removing any
bounding boxes that strictly enclose other boxes (i.e., are strict supersets).
| extract_forms_from_pdfium_page | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/pdf/pdfium.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/pdf/pdfium.py | Apache-2.0 |
def __init__(
self,
host: str,
port: int,
db: int = 0,
max_retries: int = 0,
max_backoff: int = 32,
connection_timeout: int = 300,
max_pool_size: int = 128,
use_ssl: bool = False,
):
"""
Initialize the messaging client with conn... |
Initialize the messaging client with connection parameters.
| __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/client_base.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/client_base.py | Apache-2.0 |
def get_client(self):
"""
Returns the client instance, reconnecting if necessary.
Returns:
The client instance.
""" |
Returns the client instance, reconnecting if necessary.
Returns:
The client instance.
| get_client | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/client_base.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/client_base.py | Apache-2.0 |
def ping(self) -> bool:
"""
Checks if the server is responsive.
Returns:
True if the server responds to a ping, False otherwise.
""" |
Checks if the server is responsive.
Returns:
True if the server responds to a ping, False otherwise.
| ping | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/client_base.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/client_base.py | Apache-2.0 |
def fetch_message(
self, job_index: str, timeout: Tuple[int, float] = (100, None), override_fetch_mode: FetchMode = None
) -> ResponseSchema:
"""
Fetches a message from the specified queue with retries on failure.
Parameters:
job_index (str): The index of the job to fetc... |
Fetches a message from the specified queue with retries on failure.
Parameters:
job_index (str): The index of the job to fetch the message for.
timeout (float): The timeout in seconds for blocking until a message is available.
override_fetch_mode: Optional; override... | fetch_message | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/client_base.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/client_base.py | Apache-2.0 |
def __init__(
self,
host: str,
port: int,
db: int = 0,
max_retries: int = 3,
max_backoff: int = 32,
connection_timeout: int = 300,
max_pool_size: int = 128,
use_ssl: bool = False,
redis_allocator: Callable[..., redis.Redis] = redis.Redis,
... |
Initializes the Redis client with connection pooling, retry/backoff configuration,
and optional caching for non-destructive or hybrid fetch modes.
Parameters
----------
host : str
The Redis server hostname or IP address.
port : int
The Redis serv... | __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _connect(self) -> None:
"""
Attempts to reconnect to the Redis server by allocating a new client from the pool.
Returns
-------
None
Raises
------
ConnectionError
If the newly allocated client fails to respond to a ping.
"""
... |
Attempts to reconnect to the Redis server by allocating a new client from the pool.
Returns
-------
None
Raises
------
ConnectionError
If the newly allocated client fails to respond to a ping.
| _connect | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def max_retries(self, value: int) -> None:
"""
Sets the maximum number of allowed retries for Redis operations.
Parameters
----------
value : int
The new maximum retries value; must be a non-negative integer.
Raises
------
ValueError
... |
Sets the maximum number of allowed retries for Redis operations.
Parameters
----------
value : int
The new maximum retries value; must be a non-negative integer.
Raises
------
ValueError
If the value is not a non-negative integer.
... | max_retries | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def get_client(self) -> redis.Redis:
"""
Returns a Redis client instance, attempting reconnection if the current client is invalid.
Returns
-------
redis.Redis
The active Redis client instance.
Raises
------
RuntimeError
If no val... |
Returns a Redis client instance, attempting reconnection if the current client is invalid.
Returns
-------
redis.Redis
The active Redis client instance.
Raises
------
RuntimeError
If no valid client can be established.
| get_client | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def ping(self) -> bool:
"""
Checks if the Redis client connection is alive by issuing a PING command.
Returns
-------
bool
True if the ping is successful, False otherwise.
"""
if self._client is None:
logger.debug("Ping check: No client in... |
Checks if the Redis client connection is alive by issuing a PING command.
Returns
-------
bool
True if the ping is successful, False otherwise.
| ping | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _check_response(
self, channel_name: str, timeout: float
) -> Tuple[Optional[Dict[str, Any]], Optional[int], Optional[int]]:
"""
Checks for a response from a Redis queue and processes it into a message and its fragmentation metadata.
Parameters
----------
channel... |
Checks for a response from a Redis queue and processes it into a message and its fragmentation metadata.
Parameters
----------
channel_name : str
The Redis channel from which to retrieve the response.
timeout : float
The time in seconds to wait for a res... | _check_response | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _fetch_first_or_all_fragments_destructive(
self, channel_name: str, timeout: float
) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
"""
Fetches message fragments destructively using BLPOP, returning either a single message
or a list of fragments if the message is split.
... |
Fetches message fragments destructively using BLPOP, returning either a single message
or a list of fragments if the message is split.
Parameters
----------
channel_name : str
The Redis list key from which to pop the message.
timeout : float
The ... | _fetch_first_or_all_fragments_destructive | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _fetch_fragments_non_destructive(self, channel_name: str, timeout: float) -> List[Dict[str, Any]]:
"""
Fetches all message fragments non-destructively by polling the Redis list. Uses LINDEX,
LLEN, and LRANGE to collect fragments, respecting a total timeout.
Parameters
------... |
Fetches all message fragments non-destructively by polling the Redis list. Uses LINDEX,
LLEN, and LRANGE to collect fragments, respecting a total timeout.
Parameters
----------
channel_name : str
The Redis list key where fragments are stored.
timeout : float... | _fetch_fragments_non_destructive | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _fetch_fragments_cached(self, channel_name: str, timeout: float) -> List[Dict[str, Any]]:
"""
Attempts to retrieve cached message fragments; if unsuccessful, fetches destructively from Redis
and writes the result to cache.
Parameters
----------
channel_name : str
... |
Attempts to retrieve cached message fragments; if unsuccessful, fetches destructively from Redis
and writes the result to cache.
Parameters
----------
channel_name : str
The Redis channel key to fetch the message from.
timeout : float
The timeout... | _fetch_fragments_cached | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def fetch_message(
self, channel_name: str, timeout: float = 10, override_fetch_mode: Optional["FetchMode"] = None
) -> Optional[Dict[str, Any]]:
"""
Fetches a complete message from Redis. It handles fragmentation according to the specified
or configured fetch mode and retries on con... |
Fetches a complete message from Redis. It handles fragmentation according to the specified
or configured fetch mode and retries on connection errors.
Parameters
----------
channel_name : str
The Redis channel key from which to fetch the message.
timeout : fl... | fetch_message | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _combine_fragments(fragments: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Combines a list of message fragments into a single message by merging shared metadata
and concatenating the fragment data lists.
Parameters
----------
fragments : List[Dict[str, Any]]
... |
Combines a list of message fragments into a single message by merging shared metadata
and concatenating the fragment data lists.
Parameters
----------
fragments : List[Dict[str, Any]]
A list of fragment dictionaries containing at least a 'data' key and optional meta... | _combine_fragments | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/redis/redis_client.py | Apache-2.0 |
def _generate_url(host: str, port: int) -> str:
"""
Constructs a base URL from host and port, intelligently handling schemes and existing ports.
Parameters
----------
host : str
Hostname, IP address, or full URL (e.g., "localhost", "192.168.1.100",
"http:... |
Constructs a base URL from host and port, intelligently handling schemes and existing ports.
Parameters
----------
host : str
Hostname, IP address, or full URL (e.g., "localhost", "192.168.1.100",
"http://example.com", "https://api.example.com:8443/v1").
... | _generate_url | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | Apache-2.0 |
def max_retries(self, value: int) -> None:
"""
Sets the maximum number of retry attempts.
Parameters
----------
value : int
The new maximum number of retries. Must be a non-negative integer.
Raises
------
ValueError
If value is no... |
Sets the maximum number of retry attempts.
Parameters
----------
value : int
The new maximum number of retries. Must be a non-negative integer.
Raises
------
ValueError
If value is not a non-negative integer.
| max_retries | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | Apache-2.0 |
def ping(self) -> "ResponseSchema":
"""
Checks if the HTTP server endpoint is responsive using an HTTP GET request.
Returns
-------
ResponseSchema
An object encapsulating the outcome:
- response_code = 0 indicates success (HTTP status code < 400).
... |
Checks if the HTTP server endpoint is responsive using an HTTP GET request.
Returns
-------
ResponseSchema
An object encapsulating the outcome:
- response_code = 0 indicates success (HTTP status code < 400).
- response_code = 1 indicates failure, wit... | ping | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | Apache-2.0 |
def fetch_message(
self, job_id: str, timeout: Optional[Union[float, Tuple[float, float]]] = None
) -> "ResponseSchema":
"""
Fetches a job result message from the server's fetch endpoint.
Handles retries for connection errors and non-terminal HTTP errors based on the max_retries con... |
Fetches a job result message from the server's fetch endpoint.
Handles retries for connection errors and non-terminal HTTP errors based on the max_retries configuration.
Specific HTTP statuses are treated as immediate failures (terminal) or as job not ready (HTTP 202).
Parameters
... | fetch_message | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/service_clients/rest/rest_client.py | Apache-2.0 |
def remove_url_endpoints(url) -> str:
"""Some configurations provide the full endpoint in the URL.
Ex: http://deplot:8000/v1/chat/completions. For hitting the
health endpoint we need to get just the hostname:port combo
that we can append the health/ready endpoint to so we attempt
to parse that infor... | Some configurations provide the full endpoint in the URL.
Ex: http://deplot:8000/v1/chat/completions. For hitting the
health endpoint we need to get just the hostname:port combo
that we can append the health/ready endpoint to so we attempt
to parse that information here.
Args:
url str: Inco... | remove_url_endpoints | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/string_processing/__init__.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/string_processing/__init__.py | Apache-2.0 |
def generate_url(url) -> str:
"""Examines the user defined URL for http*://. If that
pattern is detected the URL is used as provided by the user.
If that pattern does not exist then the assumption is made that
the endpoint is simply `http://` and that is prepended
to the user supplied endpoint.
... | Examines the user defined URL for http*://. If that
pattern is detected the URL is used as provided by the user.
If that pattern does not exist then the assumption is made that
the endpoint is simply `http://` and that is prepended
to the user supplied endpoint.
Args:
url str: Endpoint wher... | generate_url | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/string_processing/__init__.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/string_processing/__init__.py | Apache-2.0 |
def test_validate_task_with_valid_split():
"""Test with valid split task options."""
value = ['split:{"tokenizer": "intfloat/e5-large-unsupervised", "chunk_size": 300}']
result = click_validate_task(None, None, value)
assert "split" in result
assert isinstance(result["split"], SplitTask) | Test with valid split task options. | test_validate_task_with_valid_split | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_validate_task_with_valid_extract():
"""Test with valid extract task options."""
value = ['extract:{"document_type": "pdf", "extract_method": "pdfium"}']
result = click_validate_task(None, None, value)
assert "extract_pdf" in result
assert isinstance(result["extract_pdf"], ExtractTask) | Test with valid extract task options. | test_validate_task_with_valid_extract | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_validate_task_with_valid_store_task():
"""Test with valid stor task options."""
value = ['store:{"content_type": "image", "store_method": "minio", "endpoint": "localhost:9000"}']
result = click_validate_task(None, None, value)
assert "store" in result
assert isinstance(result["store"], Sto... | Test with valid stor task options. | test_validate_task_with_valid_store_task | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_validate_task_with_invalid_options():
"""Test validation failures due to incorrect options."""
value = ['split:{"split_by": "unknown_method"}']
with pytest.raises(click.BadParameter) as exc_info:
click_validate_task(None, None, value)
assert len(exc_info.value.args) == 1 | Test validation failures due to incorrect options. | test_validate_task_with_invalid_options | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_validate_task_with_incomplete_options():
"""Test validation failures due to missing required fields."""
value = ["extract:{}"] # Missing required 'document_type'
with pytest.raises(click.BadParameter) as exc_info:
click_validate_task(None, None, value)
assert len(exc_info.value.args) =... | Test validation failures due to missing required fields. | test_validate_task_with_incomplete_options | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_validate_task_with_json_error(mock_check_schema):
"""Test handling of JSON decode error."""
mock_check_schema.side_effect = json.JSONDecodeError("Expecting value", "{malformed_json", 1)
value = ['split:{"split_by": "page"']
with pytest.raises(click.BadParameter) as exc_info:
click_valid... | Test handling of JSON decode error. | test_validate_task_with_json_error | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def create_json_file(tmp_path, content):
"""Helper function to create a temp JSON file."""
file_path = tmp_path / "dataset.json"
with open(file_path, "w") as f:
json.dump(content, f)
return str(file_path) | Helper function to create a temp JSON file. | create_json_file | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def dataset(tmp_path):
"""Fixture to create a default dataset file."""
content = {"sampled_files": ["file1.txt", "file2.txt", "file3.txt"]}
return create_json_file(tmp_path, content) | Fixture to create a default dataset file. | dataset | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_load_valid_dataset(dataset):
"""Test loading a valid dataset without shuffling."""
files = pre_process_dataset(dataset, shuffle_dataset=False)
assert files == ["file1.txt", "file2.txt", "file3.txt"] | Test loading a valid dataset without shuffling. | test_load_valid_dataset | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_load_and_shuffle_dataset(tmp_path):
"""Test loading and shuffling a larger dataset."""
# Create a larger dataset
content = {"sampled_files": [f"file{i}.txt" for i in range(100)]} # Creating 100 unique files
dataset_path = create_json_file(tmp_path, content) # Use the helper function to create... | Test loading and shuffling a larger dataset. | test_load_and_shuffle_dataset | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_missing_dataset_file(tmp_path):
"""Test behavior with a non-existent dataset file."""
non_existent_file = tmp_path / "missing.json"
with pytest.raises(click.BadParameter):
pre_process_dataset(str(non_existent_file), shuffle_dataset=False) | Test behavior with a non-existent dataset file. | test_missing_dataset_file | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_malformed_json_dataset(tmp_path):
"""Test behavior with a malformed JSON file."""
bad_json_path = tmp_path / "malformed.json"
with open(bad_json_path, "w") as f:
f.write("{badly: 'formatted', json: true")
with pytest.raises(click.BadParameter):
pre_process_dataset(str(bad_json_p... | Test behavior with a malformed JSON file. | test_malformed_json_dataset | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_empty_file_list(tmp_path):
"""Test behavior with a JSON file that contains an empty 'sampled_files' list."""
content = {"sampled_files": []}
file_path = create_json_file(tmp_path, content)
files = pre_process_dataset(file_path, shuffle_dataset=True)
assert files == [], "Expected an empty li... | Test behavior with a JSON file that contains an empty 'sampled_files' list. | test_empty_file_list | python | NVIDIA/nv-ingest | client/client_tests/cli/util/test_click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/cli/util/test_click.py | Apache-2.0 |
def test_job_count_with_multiple_jobs(nv_ingest_client_with_jobs):
"""Test that job_count accurately reflects the number of jobs."""
expected_count = 7 # Adjust based on the number of jobs added in the fixture
assert nv_ingest_client_with_jobs.job_count() == expected_count, f"Job count should be {expected_... | Test that job_count accurately reflects the number of jobs. | test_job_count_with_multiple_jobs | python | NVIDIA/nv-ingest | client/client_tests/client/test_client.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/client/test_client.py | Apache-2.0 |
def test_ingest(ingestor, mock_client):
"""
Test the ingest method for the successful processing path.
Verifies that the ingestor correctly adds jobs (if applicable) and
calls the client's concurrent processing method, returning the
successful results.
"""
# Arrange
# Mock the methods e... |
Test the ingest method for the successful processing path.
Verifies that the ingestor correctly adds jobs (if applicable) and
calls the client's concurrent processing method, returning the
successful results.
| test_ingest | python | NVIDIA/nv-ingest | client/client_tests/client/test_interface.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/client/test_interface.py | Apache-2.0 |
def test_ingest_return_failures(ingestor, mock_client):
"""
Test the ingest method when return_failures=True.
Verifies that the ingestor calls the client's concurrent processing
method with return_failures=True and correctly returns both results
and failures.
"""
# Arrange
job_indices =... |
Test the ingest method when return_failures=True.
Verifies that the ingestor calls the client's concurrent processing
method with return_failures=True and correctly returns both results
and failures.
| test_ingest_return_failures | python | NVIDIA/nv-ingest | client/client_tests/client/test_interface.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/client/test_interface.py | Apache-2.0 |
def test_audio_extraction_task_to_dict(sample_task):
"""Test conversion of AudioExtractionTask to dictionary."""
expected_dict = {
"type": "audio_data_extract",
"task_properties": {
"auth_token": "test_token",
"grpc_endpoint": "localhost:50051",
"infer_protoco... | Test conversion of AudioExtractionTask to dictionary. | test_audio_extraction_task_to_dict | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_audio_extraction.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_audio_extraction.py | Apache-2.0 |
def test_valid_schema_initialization():
"""Test valid initialization of CaptionTaskSchema with all fields."""
schema = CaptionTaskSchema(api_key="test_key", endpoint_url="http://example.com", prompt="Generate a caption")
assert schema.api_key == "test_key"
assert schema.endpoint_url == "http://example.c... | Test valid initialization of CaptionTaskSchema with all fields. | test_valid_schema_initialization | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_empty_schema_initialization():
"""Test valid initialization of CaptionTaskSchema with no fields."""
schema = CaptionTaskSchema()
assert schema.api_key is None
assert schema.endpoint_url is None
assert schema.prompt is None | Test valid initialization of CaptionTaskSchema with no fields. | test_empty_schema_initialization | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_schema_invalid_extra_field():
"""Test that CaptionTaskSchema raises an error with extra fields."""
try:
CaptionTaskSchema(api_key="test_key", extra_field="invalid")
except ValidationError as e:
assert "extra_field" in str(e) | Test that CaptionTaskSchema raises an error with extra fields. | test_schema_invalid_extra_field | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_initialization():
"""Test initializing CaptionTask with all fields."""
task = CaptionTask(api_key="test_key", endpoint_url="http://example.com", prompt="Generate a caption")
assert task._api_key == "test_key"
assert task._endpoint_url == "http://example.com"
assert task._prompt... | Test initializing CaptionTask with all fields. | test_caption_task_initialization | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_empty_initialization():
"""Test initializing CaptionTask with no fields."""
task = CaptionTask()
assert task._api_key is None
assert task._endpoint_url is None
assert task._prompt is None | Test initializing CaptionTask with no fields. | test_caption_task_empty_initialization | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_str_representation_all_fields():
"""Test string representation of CaptionTask with all fields."""
task = CaptionTask(api_key="test_key", endpoint_url="http://example.com", prompt="Generate a caption")
task_str = str(task)
assert "Image Caption Task:" in task_str
assert "api_key... | Test string representation of CaptionTask with all fields. | test_caption_task_str_representation_all_fields | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_str_representation_partial_fields():
"""Test string representation of CaptionTask with partial fields."""
task = CaptionTask(api_key="test_key")
task_str = str(task)
assert "Image Caption Task:" in task_str
assert "api_key: [redacted]" in task_str
assert "endpoint_url" not ... | Test string representation of CaptionTask with partial fields. | test_caption_task_str_representation_partial_fields | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_to_dict_all_fields():
"""Test to_dict method of CaptionTask with all fields."""
task = CaptionTask(api_key="test_key", endpoint_url="http://example.com", prompt="Generate a caption")
task_dict = task.to_dict()
assert task_dict == {
"type": "caption",
"task_propertie... | Test to_dict method of CaptionTask with all fields. | test_caption_task_to_dict_all_fields | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_to_dict_partial_fields():
"""Test to_dict method of CaptionTask with partial fields."""
task = CaptionTask(api_key="test_key")
task_dict = task.to_dict()
assert task_dict == {"type": "caption", "task_properties": {"api_key": "test_key"}} | Test to_dict method of CaptionTask with partial fields. | test_caption_task_to_dict_partial_fields | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def test_caption_task_to_dict_empty_fields():
"""Test to_dict method of CaptionTask with no fields."""
task = CaptionTask()
task_dict = task.to_dict()
assert task_dict == {"type": "caption", "task_properties": {}} | Test to_dict method of CaptionTask with no fields. | test_caption_task_to_dict_empty_fields | python | NVIDIA/nv-ingest | client/client_tests/primitives/tasks/test_caption.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/primitives/tasks/test_caption.py | Apache-2.0 |
def dataset_content(tmp_path):
"""
Creates a temporary JSON file with dataset content and returns its BytesIO representation.
"""
dataset = {
"sampled_files": [str(tmp_path / f"file{i}.txt") for i in range(5)],
"metadata": {
"total_sampled_size_bytes": 5000,
"file... |
Creates a temporary JSON file with dataset content and returns its BytesIO representation.
| dataset_content | python | NVIDIA/nv-ingest | client/client_tests/util/test_dataset.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_dataset.py | Apache-2.0 |
def test_get_dataset_statistics_with_valid_dataset(dataset_content):
"""
Tests that get_dataset_statistics returns expected statistics for a valid dataset.
"""
stats = get_dataset_statistics(dataset_content)
assert "Dataset Statistics:" in stats
assert "'total_number_of_files': 5" in stats |
Tests that get_dataset_statistics returns expected statistics for a valid dataset.
| test_get_dataset_statistics_with_valid_dataset | python | NVIDIA/nv-ingest | client/client_tests/util/test_dataset.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_dataset.py | Apache-2.0 |
def test_get_dataset_files_without_shuffle(dataset_content):
"""
Tests get_dataset_files returns the correct files without shuffling.
"""
files = get_dataset_files(dataset_content, shuffle=False)
assert len(files) == 5
assert files[0].endswith("file0.txt") |
Tests get_dataset_files returns the correct files without shuffling.
| test_get_dataset_files_without_shuffle | python | NVIDIA/nv-ingest | client/client_tests/util/test_dataset.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_dataset.py | Apache-2.0 |
def test_get_dataset_files_with_shuffle(dataset_content):
"""
Tests get_dataset_files returns the correct files and shuffles them.
"""
original_files = get_dataset_files(dataset_content, shuffle=False)
shuffled_files = get_dataset_files(BytesIO(dataset_content.getvalue()), shuffle=True)
assert l... |
Tests get_dataset_files returns the correct files and shuffles them.
| test_get_dataset_files_with_shuffle | python | NVIDIA/nv-ingest | client/client_tests/util/test_dataset.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_dataset.py | Apache-2.0 |
def test_get_dataset_statistics_invalid_json():
"""
Tests get_dataset_statistics raises an error with invalid JSON.
"""
dataset_bytes = BytesIO(b"{invalid_json}")
with pytest.raises(json.JSONDecodeError):
get_dataset_statistics(dataset_bytes) |
Tests get_dataset_statistics raises an error with invalid JSON.
| test_get_dataset_statistics_invalid_json | python | NVIDIA/nv-ingest | client/client_tests/util/test_dataset.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_dataset.py | Apache-2.0 |
def test_get_dataset_files_invalid_json():
"""
Tests get_dataset_files raises an error with invalid JSON.
"""
dataset_bytes = BytesIO(b"{invalid_json}")
with pytest.raises(ValueError):
get_dataset_files(dataset_bytes) |
Tests get_dataset_files raises an error with invalid JSON.
| test_get_dataset_files_invalid_json | python | NVIDIA/nv-ingest | client/client_tests/util/test_dataset.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_dataset.py | Apache-2.0 |
def test_create_nvingest_index_params(sparse, gpu_index, gpu_search, local_index, expected_params):
"""Test that create_nvingest_index_params creates index parameters with all necessary attributes."""
index_params = create_nvingest_index_params(
sparse=sparse, gpu_index=gpu_index, gpu_search=gpu_search,... | Test that create_nvingest_index_params creates index parameters with all necessary attributes. | test_create_nvingest_index_params | python | NVIDIA/nv-ingest | client/client_tests/util/test_milvus_util.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_milvus_util.py | Apache-2.0 |
def test_filter_function_kwargs_with_extra_kwargs_ignored():
"""Test that extra kwargs are ignored and do not cause errors."""
def sample_func(a, b):
pass
kwargs = {"a": 10, "b": 20, "extra": "ignored"}
result = filter_function_kwargs(sample_func, **kwargs)
assert result == {"a": 10, "b": ... | Test that extra kwargs are ignored and do not cause errors. | test_filter_function_kwargs_with_extra_kwargs_ignored | python | NVIDIA/nv-ingest | client/client_tests/util/test_util.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_util.py | Apache-2.0 |
def test_filter_function_kwargs_all_args_matching():
"""Test that all kwargs are returned if they all match the function parameters."""
def sample_func(a, b, c):
pass
kwargs = {"a": 5, "b": 10, "c": 15}
result = filter_function_kwargs(sample_func, **kwargs)
assert result == kwargs, "Should... | Test that all kwargs are returned if they all match the function parameters. | test_filter_function_kwargs_all_args_matching | python | NVIDIA/nv-ingest | client/client_tests/util/test_util.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/test_util.py | Apache-2.0 |
def test_get_or_infer_file_type_fallback_mime(mock_magic):
"""
Test that the function falls back on MIME type detection for unrecognized extensions.
"""
mock_magic.return_value = "text/plain"
file_path = "/fake/path/to/unknown"
get_or_infer_file_type(file_path) |
Test that the function falls back on MIME type detection for unrecognized extensions.
| test_get_or_infer_file_type_fallback_mime | python | NVIDIA/nv-ingest | client/client_tests/util/file_processing/test_extract.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/file_processing/test_extract.py | Apache-2.0 |
def test_get_or_infer_file_type_unrecognized_extension_and_mime(mock_magic):
"""
Test that the function raises a ValueError for unrecognized extensions and undetectable MIME types.
"""
mock_magic.return_value = "application/octet-stream"
file_path = "/fake/path/to/unknown.filetype"
with pytest.r... |
Test that the function raises a ValueError for unrecognized extensions and undetectable MIME types.
| test_get_or_infer_file_type_unrecognized_extension_and_mime | python | NVIDIA/nv-ingest | client/client_tests/util/file_processing/test_extract.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/client_tests/util/file_processing/test_extract.py | Apache-2.0 |
def debug_print_click_options(ctx: click.Context) -> None:
"""
Retrieves all options from the Click context and pretty prints them.
Parameters
----------
ctx : click.Context
The Click context object from which to retrieve the command options.
"""
click_options: Dict[str, Any] = {}
... |
Retrieves all options from the Click context and pretty prints them.
Parameters
----------
ctx : click.Context
The Click context object from which to retrieve the command options.
| debug_print_click_options | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def click_validate_file_exists(
ctx: click.Context, param: click.Parameter, value: Union[str, List[str], None]
) -> List[str]:
"""
Validates that the given file(s) exist.
Parameters
----------
ctx : click.Context
The Click context.
param : click.Parameter
The parameter assoc... |
Validates that the given file(s) exist.
Parameters
----------
ctx : click.Context
The Click context.
param : click.Parameter
The parameter associated with the file option.
value : Union[str, List[str], None]
A file path or a list of file paths.
Returns
-------
... | click_validate_file_exists | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def parse_task_options(task_id: str, options_str: str) -> Dict[str, Any]:
"""
Parse the task options string as JSON.
Parameters
----------
task_id : str
The identifier of the task for which options are being parsed.
options_str : str
The string containing JSON options.
Retu... |
Parse the task options string as JSON.
Parameters
----------
task_id : str
The identifier of the task for which options are being parsed.
options_str : str
The string containing JSON options.
Returns
-------
Dict[str, Any]
The parsed options as a dictionary.
... | parse_task_options | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def click_validate_task(ctx: click.Context, param: click.Parameter, value: List[str]) -> Dict[str, TaskType]:
"""
Validates and processes task definitions provided as strings.
Each task definition should be in the format "<task_id>:<json_options>".
If the separator ':' is missing, an empty JSON options... |
Validates and processes task definitions provided as strings.
Each task definition should be in the format "<task_id>:<json_options>".
If the separator ':' is missing, an empty JSON options dictionary is assumed.
The function uses a schema check (via check_schema) for validation and
instantiates t... | click_validate_task | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def click_validate_batch_size(ctx: click.Context, param: click.Parameter, value: int) -> int:
"""
Validates that the batch size is at least 1.
Parameters
----------
ctx : click.Context
The Click context.
param : click.Parameter
The parameter associated with the batch size option... |
Validates that the batch size is at least 1.
Parameters
----------
ctx : click.Context
The Click context.
param : click.Parameter
The parameter associated with the batch size option.
value : int
The batch size value provided.
Returns
-------
int
The... | click_validate_batch_size | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def pre_process_dataset(dataset_json: str, shuffle_dataset: bool) -> List[str]:
"""
Loads a dataset from a JSON file and optionally shuffles the list of files.
Parameters
----------
dataset_json : str
The path to the dataset JSON file.
shuffle_dataset : bool
Whether to shuffle t... |
Loads a dataset from a JSON file and optionally shuffles the list of files.
Parameters
----------
dataset_json : str
The path to the dataset JSON file.
shuffle_dataset : bool
Whether to shuffle the dataset before processing.
Returns
-------
List[str]
The list o... | pre_process_dataset | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def click_match_and_validate_files(ctx: click.Context, param: click.Parameter, value: List[str]) -> List[str]:
"""
Matches and validates files based on the provided file source patterns.
Parameters
----------
ctx : click.Context
The Click context.
param : click.Parameter
The par... |
Matches and validates files based on the provided file source patterns.
Parameters
----------
ctx : click.Context
The Click context.
param : click.Parameter
The parameter associated with the file matching option.
value : List[str]
A list of file source patterns to match... | click_match_and_validate_files | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/click.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/click.py | Apache-2.0 |
def report_stage_statistics(stage_elapsed_times: defaultdict, total_trace_elapsed: float, abs_elapsed: float) -> None:
"""
Reports the statistics for each processing stage, including average, median, total time spent,
and their respective percentages of the total processing time.
Parameters
-------... |
Reports the statistics for each processing stage, including average, median, total time spent,
and their respective percentages of the total processing time.
Parameters
----------
stage_elapsed_times : defaultdict(list)
A defaultdict containing lists of elapsed times for each processing st... | report_stage_statistics | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/processing.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/processing.py | Apache-2.0 |
def report_overall_speed(total_pages_processed: int, start_time_ns: int, total_files: int) -> None:
"""
Report the overall processing speed based on the number of pages and files processed.
This function calculates the total elapsed time from the start of processing and reports the throughput
in terms ... |
Report the overall processing speed based on the number of pages and files processed.
This function calculates the total elapsed time from the start of processing and reports the throughput
in terms of pages and files processed per second.
Parameters
----------
total_pages_processed : int
... | report_overall_speed | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/processing.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/processing.py | Apache-2.0 |
def report_statistics(
start_time_ns: int,
stage_elapsed_times: defaultdict,
total_pages_processed: int,
total_files: int,
) -> None:
"""
Aggregate and report statistics for the entire processing session.
This function calculates the absolute elapsed time from the start of processing to the... |
Aggregate and report statistics for the entire processing session.
This function calculates the absolute elapsed time from the start of processing to the current time and
the total time taken by all stages. It then reports detailed stage statistics along with overall
processing throughput.
Parame... | report_statistics | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/processing.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/processing.py | Apache-2.0 |
def process_response(response: Dict[str, Any], stage_elapsed_times: defaultdict) -> None:
"""
Process the response to extract trace data and calculate elapsed time for each stage.
This function iterates over trace data in the response, identifies entry and exit times for each stage,
calculates the elap... |
Process the response to extract trace data and calculate elapsed time for each stage.
This function iterates over trace data in the response, identifies entry and exit times for each stage,
calculates the elapsed time, and appends the elapsed time to the corresponding stage in the provided
`stage_elap... | process_response | python | NVIDIA/nv-ingest | client/src/nv_ingest_client/cli/util/processing.py | https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/processing.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.