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 create_audio_inference_client(
endpoints: Tuple[str, str],
infer_protocol: Optional[str] = None,
auth_token: Optional[str] = None,
function_id: Optional[str] = None,
use_ssl: bool = False,
ssl_cert: Optional[str] = None,
):
"""
Create a ParakeetClient for interfacing with an audio mo... |
Create a ParakeetClient for interfacing with an audio model inference server.
Parameters
----------
endpoints : tuple
A tuple containing the gRPC and HTTP endpoints. Only the gRPC endpoint is used.
infer_protocol : str, optional
The protocol to use ("grpc" or "http").
If no... | create_audio_inference_client | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/parakeet.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/parakeet.py | Apache-2.0 |
def prepare_data_for_inference(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Prepare input data for embedding inference. Ensures that a 'prompts' key is provided
and that its value is a list.
Raises
------
KeyError
If the 'prompts' key is missing.
... |
Prepare input data for embedding inference. Ensures that a 'prompts' key is provided
and that its value is a list.
Raises
------
KeyError
If the 'prompts' key is missing.
| prepare_data_for_inference | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py | Apache-2.0 |
def format_input(
self, data: Dict[str, Any], protocol: str, max_batch_size: int, **kwargs
) -> Tuple[List[Any], List[Dict[str, Any]]]:
"""
Format the input payload for the embedding endpoint. This method constructs one payload per batch,
where each payload includes a list of text pr... |
Format the input payload for the embedding endpoint. This method constructs one payload per batch,
where each payload includes a list of text prompts.
Additionally, it returns batch data that preserves the original order of prompts.
Parameters
----------
data : dict
... | format_input | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py | Apache-2.0 |
def parse_output(self, response: Any, protocol: str, data: Optional[Dict[str, Any]] = None, **kwargs) -> Any:
"""
Parse the HTTP response from the embedding endpoint. Expects a response structure with a "data" key.
Parameters
----------
response : Any
The raw HTTP re... |
Parse the HTTP response from the embedding endpoint. Expects a response structure with a "data" key.
Parameters
----------
response : Any
The raw HTTP response (assumed to be already decoded as JSON).
protocol : str
Only "http" is supported.
data... | parse_output | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/text_embedding.py | Apache-2.0 |
def prepare_data_for_inference(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Prepare input data for VLM inference. Accepts either a single base64 image or a list of images.
Ensures that a 'prompt' is provided.
Raises
------
KeyError
If neither "base64_im... |
Prepare input data for VLM inference. Accepts either a single base64 image or a list of images.
Ensures that a 'prompt' is provided.
Raises
------
KeyError
If neither "base64_image" nor "base64_images" is provided or if "prompt" is missing.
ValueError
... | prepare_data_for_inference | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/vlm.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/vlm.py | Apache-2.0 |
def format_input(
self, data: Dict[str, Any], protocol: str, max_batch_size: int, **kwargs
) -> Tuple[List[Any], List[Dict[str, Any]]]:
"""
Format the input payload for the VLM endpoint. This method constructs one payload per batch,
where each payload includes one message per image i... |
Format the input payload for the VLM endpoint. This method constructs one payload per batch,
where each payload includes one message per image in the batch.
Additionally, it returns batch data that preserves the original order of images by including
the list of base64 images and the pro... | format_input | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/vlm.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/vlm.py | Apache-2.0 |
def parse_output(self, response: Any, protocol: str, data: Optional[Dict[str, Any]] = None, **kwargs) -> Any:
"""
Parse the HTTP response from the VLM endpoint. Expects a response structure with a "choices" key.
Parameters
----------
response : Any
The raw HTTP respo... |
Parse the HTTP response from the VLM endpoint. Expects a response structure with a "choices" key.
Parameters
----------
response : Any
The raw HTTP response (assumed to be already decoded as JSON).
protocol : str
Only "http" is supported.
data : ... | parse_output | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/vlm.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/vlm.py | Apache-2.0 |
def __init__(
self,
image_preproc_width: Optional[int] = None,
image_preproc_height: Optional[int] = None,
nim_max_image_size: Optional[int] = None,
num_classes: Optional[int] = None,
conf_threshold: Optional[float] = None,
iou_threshold: Optional[float] = None,
... |
Initialize the YOLOX model interface.
Parameters
----------
| __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def prepare_data_for_inference(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Prepare input data for inference by resizing images and storing their original shapes.
Parameters
----------
data : dict
The input data containing a list of images.
Returns
... |
Prepare input data for inference by resizing images and storing their original shapes.
Parameters
----------
data : dict
The input data containing a list of images.
Returns
-------
dict
The updated data dictionary with resized images and... | prepare_data_for_inference | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def format_input(
self, data: Dict[str, Any], protocol: str, max_batch_size: int, **kwargs
) -> Tuple[List[Any], List[Dict[str, Any]]]:
"""
Format input data for the specified protocol, returning a tuple of:
(formatted_batches, formatted_batch_data)
where:
- For g... |
Format input data for the specified protocol, returning a tuple of:
(formatted_batches, formatted_batch_data)
where:
- For gRPC: formatted_batches is a list of NumPy arrays, each of shape (B, H, W, C)
with B <= max_batch_size.
- For HTTP: formatted_batches is a... | format_input | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def parse_output(self, response: Any, protocol: str, data: Optional[Dict[str, Any]] = None, **kwargs) -> Any:
"""
Parse the output from the model's inference response.
Parameters
----------
response : Any
The response from the model inference.
protocol : str
... |
Parse the output from the model's inference response.
Parameters
----------
response : Any
The response from the model inference.
protocol : str
The protocol used ("grpc" or "http").
data : dict, optional
Additional input data passed ... | parse_output | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def process_inference_results(self, output: Any, protocol: str, **kwargs) -> List[Dict[str, Any]]:
"""
Process the results of the Yolox model inference and return the final annotations.
Parameters
----------
output_array : np.ndarray
The raw output from the Yolox mod... |
Process the results of the Yolox model inference and return the final annotations.
Parameters
----------
output_array : np.ndarray
The raw output from the Yolox model.
kwargs : dict
Additional parameters for processing, including thresholds and number of... | process_inference_results | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def __init__(self, yolox_model_name: str = "nemoretriever-page-elements-v2"):
"""
Initialize the yolox-page-elements model interface.
"""
if yolox_model_name.endswith("-v1"):
num_classes = YOLOX_PAGE_V1_NUM_CLASSES
final_score = YOLOX_PAGE_V1_FINAL_SCORE
... |
Initialize the yolox-page-elements model interface.
| __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def name(
self,
) -> str:
"""
Returns the name of the Yolox model interface.
Returns
-------
str
The name of the model interface.
"""
return "yolox-page-elements" |
Returns the name of the Yolox model interface.
Returns
-------
str
The name of the model interface.
| name | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def __init__(self, yolox_version: Optional[str] = None):
"""
Initialize the yolox-graphic-elements model interface.
"""
if yolox_version and (
packaging.version.Version(yolox_version) >= packaging.version.Version("1.2.0-rc5") # gtc release
):
image_prepro... |
Initialize the yolox-graphic-elements model interface.
| __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def postprocess_results(
results, original_image_shapes, image_preproc_width, image_preproc_height, class_labels, min_score=0.0
):
"""
For each item (==image) in results, computes annotations in the form
{"table": [[0.0107, 0.0859, 0.7537, 0.1219, 0.9861], ...],
"figure": [...],
"title": [... |
For each item (==image) in results, computes annotations in the form
{"table": [[0.0107, 0.0859, 0.7537, 0.1219, 0.9861], ...],
"figure": [...],
"title": [...]
}
where each list of 5 floats represents a bounding box in the format [x1, y1, x2, y2, confidence]
Keep only bboxes with h... | postprocess_results | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def expand_table_bboxes(annotation_dict, labels=None):
"""
Additional preprocessing for tables: extend the upper bounds to capture titles if any.
Args:
annotation_dict: output of postprocess_results, a dictionary with keys "table", "figure", "title"
Returns:
annotation_dict: same as inp... |
Additional preprocessing for tables: extend the upper bounds to capture titles if any.
Args:
annotation_dict: output of postprocess_results, a dictionary with keys "table", "figure", "title"
Returns:
annotation_dict: same as input, with expanded bboxes for charts
| expand_table_bboxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def expand_chart_bboxes(annotation_dict, labels=None):
"""
Expand bounding boxes of charts and titles based on the bounding boxes of the other class.
Args:
annotation_dict: output of postprocess_results, a dictionary with keys "table", "figure", "title"
Returns:
annotation_dict: same as... |
Expand bounding boxes of charts and titles based on the bounding boxes of the other class.
Args:
annotation_dict: output of postprocess_results, a dictionary with keys "table", "figure", "title"
Returns:
annotation_dict: same as input, with expanded bboxes for charts
| expand_chart_bboxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def weighted_boxes_fusion(
boxes_list,
scores_list,
labels_list,
iou_thr=0.5,
skip_box_thr=0.0,
conf_type="avg",
merge_type="weighted",
class_agnostic=False,
):
"""
Custom wbf implementation that supports a class_agnostic mode and a biggest box fusion.
Boxes are expected to b... |
Custom wbf implementation that supports a class_agnostic mode and a biggest box fusion.
Boxes are expected to be in normalized (x0, y0, x1, y1) format.
Args:
boxes_list (list[np array[n x 4]]): List of boxes. One list per model.
scores_list (list[np array[n]]): List of confidences.
... | weighted_boxes_fusion | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def prefilter_boxes(boxes, scores, labels, weights, thr, class_agnostic=False):
"""
Reformats and filters boxes.
Output is a dict of boxes to merge separately.
Args:
boxes (list[np array[n x 4]]): List of boxes. One list per model.
scores (list[np array[n]]): List of confidences.
... |
Reformats and filters boxes.
Output is a dict of boxes to merge separately.
Args:
boxes (list[np array[n x 4]]): List of boxes. One list per model.
scores (list[np array[n]]): List of confidences.
labels (list[np array[n]]): List of labels.
weights (list): Model weights.
... | prefilter_boxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def find_matching_box_fast(boxes_list, new_box, match_iou):
"""
Reimplementation of find_matching_box with numpy instead of loops. Gives significant speed up for larger arrays
(~100x). This was previously the bottleneck since the function is called for every entry in the array.
"""
def bb_iou_array... |
Reimplementation of find_matching_box with numpy instead of loops. Gives significant speed up for larger arrays
(~100x). This was previously the bottleneck since the function is called for every entry in the array.
| find_matching_box_fast | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def get_biggest_box(boxes, conf_type="avg"):
"""
Merges boxes by using the biggest box.
Args:
boxes (np array [n x 8]): Boxes to merge.
conf_type (str, optional): Confidence merging type. Defaults to "avg".
Returns:
np array [8]: Merged box.
"""
box = np.zeros(8, dtype=... |
Merges boxes by using the biggest box.
Args:
boxes (np array [n x 8]): Boxes to merge.
conf_type (str, optional): Confidence merging type. Defaults to "avg".
Returns:
np array [8]: Merged box.
| get_biggest_box | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def merge_labels(labels, confs):
"""
Custom function for merging labels.
If all labels are the same, return the unique value.
Else, return the label of the most confident non-title (class 2) box.
Args:
labels (np array [n]): Labels.
confs (np array [n]): Confidence.
Returns:
... |
Custom function for merging labels.
If all labels are the same, return the unique value.
Else, return the label of the most confident non-title (class 2) box.
Args:
labels (np array [n]): Labels.
confs (np array [n]): Confidence.
Returns:
int: Label.
| merge_labels | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def get_weighted_box(boxes, conf_type="avg"):
"""
Merges boxes by using the weighted fusion.
Args:
boxes (np array [n x 8]): Boxes to merge.
conf_type (str, optional): Confidence merging type. Defaults to "avg".
Returns:
np array [8]: Merged box.
"""
box = np.zeros(8, d... |
Merges boxes by using the weighted fusion.
Args:
boxes (np array [n x 8]): Boxes to merge.
conf_type (str, optional): Confidence merging type. Defaults to "avg".
Returns:
np array [8]: Merged box.
| get_weighted_box | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def batched_overlaps(A, B):
"""
Calculate the Intersection over Union (IoU) between
two sets of bounding boxes in a batched manner.
Normalization is modified to only use the area of A boxes, hence computing the overlaps.
Args:
A (ndarray): Array of bounding boxes of shape (N, 4) in format [x... |
Calculate the Intersection over Union (IoU) between
two sets of bounding boxes in a batched manner.
Normalization is modified to only use the area of A boxes, hence computing the overlaps.
Args:
A (ndarray): Array of bounding boxes of shape (N, 4) in format [x1, y1, x2, y2].
B (ndarray)... | batched_overlaps | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def find_boxes_inside(boxes, boxes_to_check, threshold=0.9):
"""
Find all boxes that are inside another box based on
the intersection area divided by the area of the smaller box,
and removes them.
"""
overlaps = batched_overlaps(boxes_to_check, boxes)
to_keep = (overlaps >= threshold).sum(0)... |
Find all boxes that are inside another box based on
the intersection area divided by the area of the smaller box,
and removes them.
| find_boxes_inside | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def get_bbox_dict_yolox_graphic(preds, shape, class_labels, threshold_=0.1) -> Dict[str, np.ndarray]:
"""
Extracts bounding boxes from YOLOX model predictions:
- Applies thresholding
- Reformats boxes
- Cleans the `other` detections: removes the ones that are included in other detections.
- If ... |
Extracts bounding boxes from YOLOX model predictions:
- Applies thresholding
- Reformats boxes
- Cleans the `other` detections: removes the ones that are included in other detections.
- If no title is found, the biggest `other` box is used if it is larger than 0.3*img_w.
Args:
preds (n... | get_bbox_dict_yolox_graphic | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def get_bbox_dict_yolox_table(preds, shape, class_labels, threshold=0.1, delta=0.0):
"""
Extracts bounding boxes from YOLOX model predictions:
- Applies thresholding
- Reformats boxes
- Reorders predictions
Args:
preds (np.ndarray): YOLOX model predictions including bounding boxes, scor... |
Extracts bounding boxes from YOLOX model predictions:
- Applies thresholding
- Reformats boxes
- Reorders predictions
Args:
preds (np.ndarray): YOLOX model predictions including bounding boxes, scores, and labels.
shape (tuple): Original image shape.
config: Model configura... | get_bbox_dict_yolox_table | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/nim/model_interface/yolox.py | Apache-2.0 |
def latency_logger(name=None):
"""
A decorator to log the elapsed time of function execution. If available, it also logs
the latency based on 'latency::ts_send' metadata in a IngestControlMessage object.
Parameters
----------
name : str, optional
Custom name to use in the log message. D... |
A decorator to log the elapsed time of function execution. If available, it also logs
the latency based on 'latency::ts_send' metadata in a IngestControlMessage object.
Parameters
----------
name : str, optional
Custom name to use in the log message. Defaults to the function's name.
| latency_logger | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/tracing/latency.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/tracing/latency.py | Apache-2.0 |
def annotate_cm(control_message: IngestControlMessage, source_id=None, **kwargs):
"""
Annotate a IngestControlMessage object with arbitrary metadata, a source ID, and a timestamp.
Each annotation will be uniquely identified by a UUID.
Parameters:
- control_message: The IngestControlMessage object t... |
Annotate a IngestControlMessage object with arbitrary metadata, a source ID, and a timestamp.
Each annotation will be uniquely identified by a UUID.
Parameters:
- control_message: The IngestControlMessage object to be annotated.
- source_id: A unique identifier for the source of the annotation. If... | annotate_cm | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/tracing/logging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/tracing/logging.py | Apache-2.0 |
def annotate_task_result(control_message, result, task_id, source_id=None, **kwargs):
"""
Annotate a IngestControlMessage object with the result of a task, identified by a task_id,
and an arbitrary number of additional key-value pairs. The result can be a TaskResultStatus
enum or a string that will be c... |
Annotate a IngestControlMessage object with the result of a task, identified by a task_id,
and an arbitrary number of additional key-value pairs. The result can be a TaskResultStatus
enum or a string that will be converted to the corresponding enum.
Parameters:
- control_message: The IngestControl... | annotate_task_result | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/tracing/logging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/tracing/logging.py | Apache-2.0 |
def traceable(trace_name=None):
"""
A decorator that adds entry and exit trace timestamps to a IngestControlMessage's metadata
based on the presence of a 'config::add_trace_tagging' flag.
This decorator checks if the 'config::add_trace_tagging' flag is set to True in the
message's metadata. If so, ... |
A decorator that adds entry and exit trace timestamps to a IngestControlMessage's metadata
based on the presence of a 'config::add_trace_tagging' flag.
This decorator checks if the 'config::add_trace_tagging' flag is set to True in the
message's metadata. If so, it records the entry and exit timestamp... | traceable | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/tracing/tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/tracing/tagging.py | Apache-2.0 |
def traceable_func(trace_name=None, dedupe=True):
"""
A decorator that injects trace information for tracking the execution of a function.
It logs the entry and exit timestamps of the function in a `trace_info` dictionary,
which can be used for performance monitoring or debugging purposes.
Paramete... |
A decorator that injects trace information for tracking the execution of a function.
It logs the entry and exit timestamps of the function in a `trace_info` dictionary,
which can be used for performance monitoring or debugging purposes.
Parameters
----------
trace_name : str, optional
... | traceable_func | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/primitives/tracing/tagging.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/primitives/tracing/tagging.py | Apache-2.0 |
def validate_endpoints(cls, values):
"""
Validates the gRPC and HTTP services for all endpoints.
Parameters
----------
values : dict
Dictionary containing the values of the attributes for the class.
Returns
-------
dict
The valida... |
Validates the gRPC and HTTP services for all endpoints.
Parameters
----------
values : dict
Dictionary containing the values of the attributes for the class.
Returns
-------
dict
The validated dictionary of values.
Raises
... | validate_endpoints | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/schemas/extract/extract_audio_schema.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/schemas/extract/extract_audio_schema.py | Apache-2.0 |
def clean_service(service):
"""Set service to None if it's an empty string or contains only spaces or quotes."""
if service is None or not service.strip() or service.strip(" \"'") == "":
return None
return service | Set service to None if it's an empty string or contains only spaces or quotes. | clean_service | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/schemas/extract/extract_audio_schema.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/schemas/extract/extract_audio_schema.py | Apache-2.0 |
def validate_endpoints(cls, values):
"""
Validates the gRPC and HTTP services for all endpoints.
Ensures that at least one service (either gRPC or HTTP) is provided
for each endpoint in the configuration.
Parameters
----------
values : dict
Dictionar... |
Validates the gRPC and HTTP services for all endpoints.
Ensures that at least one service (either gRPC or HTTP) is provided
for each endpoint in the configuration.
Parameters
----------
values : dict
Dictionary containing the values of the attributes for th... | validate_endpoints | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/schemas/extract/extract_chart_schema.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/schemas/extract/extract_chart_schema.py | Apache-2.0 |
def validate_endpoints(cls, values):
"""
Validates the gRPC and HTTP services for the yolox endpoint.
Parameters
----------
values : dict
Dictionary containing the values of the attributes for the class.
Returns
-------
dict
The v... |
Validates the gRPC and HTTP services for the yolox endpoint.
Parameters
----------
values : dict
Dictionary containing the values of the attributes for the class.
Returns
-------
dict
The validated dictionary of values.
Raises
... | validate_endpoints | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/schemas/extract/extract_table_schema.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/schemas/extract/extract_table_schema.py | Apache-2.0 |
def store_text_embeddings_internal(
df_store_ledger: pd.DataFrame,
task_config: Union[BaseModel, Dict[str, Any]],
store_config: EmbeddingStorageSchema,
execution_trace_log: Optional[Dict[str, Any]] = None,
) -> pd.DataFrame:
"""
Stores embeddings by uploading content from a DataFrame to MinIO.
... |
Stores embeddings by uploading content from a DataFrame to MinIO.
This function prepares the necessary parameters for the upload based on the task configuration,
invokes the upload routine, and returns the updated DataFrame.
Parameters
----------
df_store_ledger : pd.DataFrame
DataFra... | store_text_embeddings_internal | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/store/embed_text_upload.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/store/embed_text_upload.py | Apache-2.0 |
def _ensure_bucket_exists(client: Minio, bucket_name: str) -> None:
"""
Ensure that the specified bucket exists in MinIO, and create it if it does not.
Parameters
----------
client : Minio
An instance of the Minio client.
bucket_name : str
The name of the bucket to check or crea... |
Ensure that the specified bucket exists in MinIO, and create it if it does not.
Parameters
----------
client : Minio
An instance of the Minio client.
bucket_name : str
The name of the bucket to check or create.
| _ensure_bucket_exists | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/store/image_upload.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/store/image_upload.py | Apache-2.0 |
def _upload_images_to_minio(df: pd.DataFrame, params: Dict[str, Any]) -> pd.DataFrame:
"""
Identifies content within a DataFrame and uploads it to MinIO, updating the metadata with the uploaded URL.
This function iterates over rows of the provided DataFrame. For rows whose "document_type" is listed
in ... |
Identifies content within a DataFrame and uploads it to MinIO, updating the metadata with the uploaded URL.
This function iterates over rows of the provided DataFrame. For rows whose "document_type" is listed
in the provided 'content_types' configuration, it decodes the base64-encoded content, uploads the... | _upload_images_to_minio | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/store/image_upload.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/store/image_upload.py | Apache-2.0 |
def store_images_to_minio_internal(
df_storage_ledger: pd.DataFrame,
task_config: Dict[str, Any],
storage_config: Dict[str, Any],
execution_trace_log: Optional[List[Any]] = None,
) -> pd.DataFrame:
"""
Processes a storage ledger DataFrame to upload images (and structured content) to MinIO.
... |
Processes a storage ledger DataFrame to upload images (and structured content) to MinIO.
This function validates the input DataFrame and task configuration, then creates a mask to select rows
where the "document_type" is among the desired types specified in the configuration. If matching rows are
foun... | store_images_to_minio_internal | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/store/image_upload.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/store/image_upload.py | Apache-2.0 |
def _prepare_dataframes_mod(df: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, pd.Series]:
"""
Prepares and returns three DataFrame-related objects from the input DataFrame.
The function performs the following:
1. Checks if the DataFrame is empty or if the "document_type" column is missing.
... |
Prepares and returns three DataFrame-related objects from the input DataFrame.
The function performs the following:
1. Checks if the DataFrame is empty or if the "document_type" column is missing.
In such a case, returns the original DataFrame, an empty DataFrame, and an empty boolean Series.
... | _prepare_dataframes_mod | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/caption_image.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/caption_image.py | Apache-2.0 |
def _generate_captions(
base64_images: List[str], prompt: str, api_key: str, endpoint_url: str, model_name: str
) -> List[str]:
"""
Generates captions for a list of base64-encoded PNG images using the VLM model API.
This function performs the following steps:
1. Scales each image to meet encoding... |
Generates captions for a list of base64-encoded PNG images using the VLM model API.
This function performs the following steps:
1. Scales each image to meet encoding size requirements using `scale_image_to_encoding_size`.
2. Constructs the input payload containing the scaled images and the provide... | _generate_captions | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/caption_image.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/caption_image.py | Apache-2.0 |
def transform_image_create_vlm_caption_internal(
df_transform_ledger: pd.DataFrame,
task_config: Union[BaseModel, Dict[str, Any]],
transform_config: Any,
execution_trace_log: Optional[Dict[str, Any]] = None,
) -> pd.DataFrame:
"""
Extracts and adds captions for image content in a DataFrame using... |
Extracts and adds captions for image content in a DataFrame using the VLM model API.
This function updates the 'metadata' column for rows where the content type is "image".
It uses configuration values from task_config (or falls back to transform_config defaults)
to determine the API key, prompt, endp... | transform_image_create_vlm_caption_internal | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/caption_image.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/caption_image.py | Apache-2.0 |
def _make_async_request(
prompts: List[str],
api_key: str,
embedding_nim_endpoint: str,
embedding_model: str,
encoding_format: str,
input_type: str,
truncate: str,
filter_errors: bool,
) -> list:
"""
Interacts directly with the NIM embedding service to calculate embeddings for a ... |
Interacts directly with the NIM embedding service to calculate embeddings for a batch of prompts.
Parameters
----------
prompts : List[str]
A list of prompt strings for which embeddings are to be calculated.
api_key : str
API key for authentication with the embedding service.
e... | _make_async_request | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def _async_request_handler(
prompts: List[str],
api_key: str,
embedding_nim_endpoint: str,
embedding_model: str,
encoding_format: str,
input_type: str,
truncate: str,
filter_errors: bool,
) -> List[dict]:
"""
Gathers calculated embedding results from the NIM embedding service con... |
Gathers calculated embedding results from the NIM embedding service concurrently.
Parameters
----------
prompts : List[str]
A list of prompt batches.
api_key : str
API key for authentication.
embedding_nim_endpoint : str
Base URL for the NIM embedding service.
embed... | _async_request_handler | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def _async_runner(
prompts: List[str],
api_key: str,
embedding_nim_endpoint: str,
embedding_model: str,
encoding_format: str,
input_type: str,
truncate: str,
filter_errors: bool,
) -> dict:
"""
Concurrently launches all NIM embedding requests and flattens the results.
Parame... |
Concurrently launches all NIM embedding requests and flattens the results.
Parameters
----------
prompts : List[str]
A list of prompt batches.
api_key : str
API key for authentication.
embedding_nim_endpoint : str
Base URL for the NIM embedding service.
embedding_mo... | _async_runner | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def _add_embeddings(row, embeddings, info_msgs):
"""
Updates a DataFrame row with embedding data and associated error info.
Parameters
----------
row : pandas.Series
A row of the DataFrame.
embeddings : list
List of embeddings corresponding to DataFrame rows.
info_msgs : lis... |
Updates a DataFrame row with embedding data and associated error info.
Parameters
----------
row : pandas.Series
A row of the DataFrame.
embeddings : list
List of embeddings corresponding to DataFrame rows.
info_msgs : list
List of info message dictionaries correspondin... | _add_embeddings | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def _batch_generator(iterable: Iterable, batch_size: int = 10):
"""
Yields batches of a specified size from an iterable.
Parameters
----------
iterable : Iterable
The iterable to batch.
batch_size : int, optional
The size of each batch (default is 10).
Yields
------
... |
Yields batches of a specified size from an iterable.
Parameters
----------
iterable : Iterable
The iterable to batch.
batch_size : int, optional
The size of each batch (default is 10).
Yields
------
list
A batch of items from the iterable.
| _batch_generator | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def _concatenate_extractions_pandas(
base_df: pd.DataFrame, dataframes: List[pd.DataFrame], masks: List[pd.Series]
) -> pd.DataFrame:
"""
Concatenates processed DataFrame rows (with embeddings) with unprocessed rows from the base DataFrame.
Parameters
----------
base_df : pd.DataFrame
T... |
Concatenates processed DataFrame rows (with embeddings) with unprocessed rows from the base DataFrame.
Parameters
----------
base_df : pd.DataFrame
The original DataFrame.
dataframes : List[pd.DataFrame]
List of DataFrames that have been enriched with embeddings.
masks : List[p... | _concatenate_extractions_pandas | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def transform_create_text_embeddings_internal(
df_transform_ledger: pd.DataFrame,
task_config: Dict[str, Any],
transform_config: TextEmbeddingSchema = TextEmbeddingSchema(),
execution_trace_log: Optional[Dict] = None,
) -> Tuple[pd.DataFrame, Dict]:
"""
Generates text embeddings for supported co... |
Generates text embeddings for supported content types (TEXT, STRUCTURED, IMAGE)
from a pandas DataFrame using asynchronous requests.
Parameters
----------
df_transform_ledger : pd.DataFrame
The DataFrame containing content for embedding extraction.
task_config : Dict[str, Any]
... | transform_create_text_embeddings_internal | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/embed_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/embed_text.py | Apache-2.0 |
def transform_text_split_and_tokenize_internal(
df_transform_ledger: pd.DataFrame,
task_config: Dict[str, Any],
transform_config: TextSplitterSchema,
execution_trace_log: Optional[Dict[str, Any]],
) -> pd.DataFrame:
"""
Internal function to split and tokenize text in a ledger DataFrame.
Thi... |
Internal function to split and tokenize text in a ledger DataFrame.
This function extracts text from documents that match a filter criteria based on source types,
splits the text into chunks using the specified tokenizer, and rebuilds document records with the
split text. The resulting DataFrame conta... | transform_text_split_and_tokenize_internal | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/internal/transform/split_text.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/internal/transform/split_text.py | Apache-2.0 |
def cm_ensure_payload_not_null(control_message: IngestControlMessage):
"""
Ensures that the payload of a IngestControlMessage is not None.
Parameters
----------
control_message : IngestControlMessage
The IngestControlMessage to check.
Raises
------
ValueError
If the pay... |
Ensures that the payload of a IngestControlMessage is not None.
Parameters
----------
control_message : IngestControlMessage
The IngestControlMessage to check.
Raises
------
ValueError
If the payload is None.
| cm_ensure_payload_not_null | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/control_message/validators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/control_message/validators.py | Apache-2.0 |
def cm_set_failure(control_message: IngestControlMessage, reason: str) -> IngestControlMessage:
"""
Sets the failure metadata on a IngestControlMessage.
Parameters
----------
control_message : IngestControlMessage
The IngestControlMessage to set the failure metadata on.
reason : str
... |
Sets the failure metadata on a IngestControlMessage.
Parameters
----------
control_message : IngestControlMessage
The IngestControlMessage to set the failure metadata on.
reason : str
The reason for the failure.
Returns
-------
control_message : IngestControlMessage
... | cm_set_failure | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/control_message/validators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/control_message/validators.py | Apache-2.0 |
def merge_dict(defaults: Dict[str, Any], overrides: Dict[str, Any]) -> Dict[str, Any]:
"""
Recursively merges two dictionaries, with values from the `overrides` dictionary taking precedence.
This function merges the `overrides` dictionary into the `defaults` dictionary. If a key in both dictionaries
ha... |
Recursively merges two dictionaries, with values from the `overrides` dictionary taking precedence.
This function merges the `overrides` dictionary into the `defaults` dictionary. If a key in both dictionaries
has a dictionary as its value, the function will recursively merge those dictionaries. Otherwise... | merge_dict | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/converters/containers.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/converters/containers.py | Apache-2.0 |
def datetimefrompdfmeta(pdf_formated_date: str, keep_tz: bool = False) -> str:
"""
Convert PDF metadata formatted date string to a datetime object.
Parameters
----------
pdf_formated_date : str
A date string in standard PDF metadata format.
Example: `str("D:20211222141131-07'00'")`
... |
Convert PDF metadata formatted date string to a datetime object.
Parameters
----------
pdf_formated_date : str
A date string in standard PDF metadata format.
Example: `str("D:20211222141131-07'00'")`
keep_tz : bool, optional
Keep or remove the timezone attribute of the pars... | datetimefrompdfmeta | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/converters/datetools.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/converters/datetools.py | Apache-2.0 |
def remove_tz(datetime_obj: datetime) -> datetime:
"""
Remove timezone and add offset to a datetime object.
Parameters
----------
datetime_obj : datetime.datetime
A datetime object with or without the timezone attribute set.
Returns
-------
datetime.datetime
A datetime ... |
Remove timezone and add offset to a datetime object.
Parameters
----------
datetime_obj : datetime.datetime
A datetime object with or without the timezone attribute set.
Returns
-------
datetime.datetime
A datetime object with the timezone offset added and the timezone att... | remove_tz | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/converters/datetools.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/converters/datetools.py | Apache-2.0 |
def ingest_json_results_to_blob(result_content):
"""
Parse a JSON string or BytesIO object, combine and sort entries, and create a blob string.
Returns:
str: The generated blob string.
"""
try:
# Load the JSON data
data = json.loads(result_content) if isinstance(result_conte... |
Parse a JSON string or BytesIO object, combine and sort entries, and create a blob string.
Returns:
str: The generated blob string.
| ingest_json_results_to_blob | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/converters/formats.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/converters/formats.py | Apache-2.0 |
def detect_language(text):
"""
Detect spoken language from a string of text.
Parameters
----------
text : str
A string of text.
Returns
-------
LanguageEnum
A value from `LanguageEnum` detected language code.
"""
try:
language = langdetect.detect(text)
... |
Detect spoken language from a string of text.
Parameters
----------
text : str
A string of text.
Returns
-------
LanguageEnum
A value from `LanguageEnum` detected language code.
| detect_language | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/detectors/language.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/detectors/language.py | Apache-2.0 |
def datetools_exception_handler(func: Callable, **kwargs: Dict[str, Any]) -> Callable:
"""
A decorator that handles exceptions for date-related functions.
This decorator wraps a function that processes dates and catches any exceptions that occur during its execution.
If an exception is raised, it logs ... |
A decorator that handles exceptions for date-related functions.
This decorator wraps a function that processes dates and catches any exceptions that occur during its execution.
If an exception is raised, it logs a warning and returns the current UTC time as an ISO 8601 formatted string.
Parameters
... | datetools_exception_handler | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/converters.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/converters.py | Apache-2.0 |
def nv_ingest_node_failure_context_manager(
annotation_id: str,
payload_can_be_empty: bool = False,
raise_on_failure: bool = False,
skip_processing_if_failed: bool = True,
forward_func=None,
) -> typing.Callable:
"""
A decorator that applies a default failure context manager around a functio... |
A decorator that applies a default failure context manager around a function to manage
the execution and potential failure of operations involving IngestControlMessages.
Parameters
----------
annotation_id : str
A unique identifier used for annotating the task's result.
payload_can_be_... | nv_ingest_node_failure_context_manager | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/decorators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/decorators.py | Apache-2.0 |
def nv_ingest_source_failure_context_manager(
annotation_id: str,
payload_can_be_empty: bool = False,
raise_on_failure: bool = False,
) -> typing.Callable:
"""
A decorator that ensures any function's output is treated as a IngestControlMessage for annotation.
It applies a context manager to hand... |
A decorator that ensures any function's output is treated as a IngestControlMessage for annotation.
It applies a context manager to handle success and failure annotations based on the function's execution.
Parameters
----------
annotation_id : str
Unique identifier used for annotating the ... | nv_ingest_source_failure_context_manager | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/decorators.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/decorators.py | Apache-2.0 |
def langdetect_exception_handler(func: Callable, **kwargs: Dict[str, Any]) -> Callable:
"""
A decorator that handles `LangDetectException` for language detection functions.
This decorator wraps a function that performs language detection and catches any `LangDetectException` that occurs
during its exec... |
A decorator that handles `LangDetectException` for language detection functions.
This decorator wraps a function that performs language detection and catches any `LangDetectException` that occurs
during its execution.
If such an exception is raised, it logs a warning and returns a default value of `La... | langdetect_exception_handler | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/detectors.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/detectors.py | Apache-2.0 |
def pdfium_exception_handler(descriptor):
"""
A decorator that handles exceptions for functions interacting with PDFium.
This decorator wraps a function and catches any exceptions that occur during its execution.
If an exception is raised, it logs a warning with a descriptor and the function name,
... |
A decorator that handles exceptions for functions interacting with PDFium.
This decorator wraps a function and catches any exceptions that occur during its execution.
If an exception is raised, it logs a warning with a descriptor and the function name,
then returns an empty list as a fallback value.
... | pdfium_exception_handler | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/pdf.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/pdf.py | Apache-2.0 |
def create_exception_tag(error_message, source_id=None):
"""
Creates a metadata tag for logging or reporting an exception.
This function generates a metadata dictionary containing information about the exception,
including the task type, status, source identifier, and error message.
The metadata is... |
Creates a metadata tag for logging or reporting an exception.
This function generates a metadata dictionary containing information about the exception,
including the task type, status, source identifier, and error message.
The metadata is validated and returned as a list containing a single entry.
... | create_exception_tag | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/pdf.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/pdf.py | Apache-2.0 |
def schema_exception_handler(func, **kwargs):
"""
A decorator that handles `ValidationError` exceptions for schema validation functions.
This decorator wraps a function that performs schema validation using Pydantic.
If a `ValidationError` is raised, it logs detailed error messages and raises a `ValueE... |
A decorator that handles `ValidationError` exceptions for schema validation functions.
This decorator wraps a function that performs schema validation using Pydantic.
If a `ValidationError` is raised, it logs detailed error messages and raises a `ValueError` with the combined error
messages.
Para... | schema_exception_handler | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/exception_handlers/schemas.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/exception_handlers/schemas.py | Apache-2.0 |
def boxes_are_close_or_overlap(b1: List[int], b2: List[int], threshold: float = 10.0) -> bool:
"""
Determine if two bounding boxes either overlap or are within a certain distance threshold.
The function expands each bounding box by `threshold` in all directions and checks
if the expanded regions overla... |
Determine if two bounding boxes either overlap or are within a certain distance threshold.
The function expands each bounding box by `threshold` in all directions and checks
if the expanded regions overlap on both the x-axis and y-axis.
Parameters
----------
b1 (tuple): The first bounding box... | boxes_are_close_or_overlap | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/clustering.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/clustering.py | Apache-2.0 |
def combine_groups_into_bboxes(
boxes: List[List[int]], groups: List[List[int]], min_num_components: int = 1
) -> List[List[int]]:
"""
Merge bounding boxes based on grouped indices.
Given:
- A list of bounding boxes (`boxes`), each in the form (xmin, ymin, xmax, ymax).
- A list of groups (`... |
Merge bounding boxes based on grouped indices.
Given:
- A list of bounding boxes (`boxes`), each in the form (xmin, ymin, xmax, ymax).
- A list of groups (`groups`), where each group is a list of indices
referring to bounding boxes in `boxes`.
For each group, this function:
1. C... | combine_groups_into_bboxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/clustering.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/clustering.py | Apache-2.0 |
def remove_superset_bboxes(bboxes: List[List[int]]) -> List[List[int]]:
"""
Remove any bounding box that strictly contains another bounding box.
Specifically, for each bounding box `box_a`, if it fully encloses
another bounding box `box_b` in all dimensions (with at least one
edge strictly larger r... |
Remove any bounding box that strictly contains another bounding box.
Specifically, for each bounding box `box_a`, if it fully encloses
another bounding box `box_b` in all dimensions (with at least one
edge strictly larger rather than exactly equal), then `box_a` is
excluded from the results.
... | remove_superset_bboxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/clustering.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/clustering.py | Apache-2.0 |
def extract_tables_and_charts_from_image(annotation_dict, original_image, page_idx, tables_and_charts):
"""
Extract and process table and chart regions from the provided image based on detection annotations.
Parameters
----------
annotation_dict : dict
A dictionary containing detected objec... |
Extract and process table and chart regions from the provided image based on detection annotations.
Parameters
----------
annotation_dict : dict
A dictionary containing detected objects and their bounding boxes, e.g. keys "table" and "chart".
original_image : np.ndarray
The origina... | extract_tables_and_charts_from_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/processing.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/processing.py | Apache-2.0 |
def extract_tables_and_charts_yolox(
pages: List[Tuple[int, np.ndarray]],
config: dict,
trace_info: Optional[List] = None,
) -> List[Tuple[int, object]]:
"""
Given a list of (page_index, image) tuples and a configuration dictionary,
this function calls the YOLOX-based inference service to extrac... |
Given a list of (page_index, image) tuples and a configuration dictionary,
this function calls the YOLOX-based inference service to extract table and chart
annotations from all pages.
Parameters
----------
pages : List[Tuple[int, np.ndarray]]
A list of tuples containing the page index ... | extract_tables_and_charts_yolox | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/processing.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/processing.py | Apache-2.0 |
def process_yolox_graphic_elements(yolox_text_dict):
"""
Process the inference results from yolox-graphic-elements model.
Parameters
----------
yolox_text : str
The result from the yolox model inference.
Returns
-------
str
The concatenated and processed chart content a... |
Process the inference results from yolox-graphic-elements model.
Parameters
----------
yolox_text : str
The result from the yolox model inference.
Returns
-------
str
The concatenated and processed chart content as a string.
| process_yolox_graphic_elements | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def match_bboxes(yolox_box, paddle_ocr_boxes, already_matched=None, delta=2.0):
"""
Associates a yolox-graphic-elements box to PaddleOCR bboxes, by taking overlapping boxes.
Criterion is iou > max_iou / delta where max_iou is the biggest found overlap.
Boxes are expeceted in format (x0, y0, x1, y1)
... |
Associates a yolox-graphic-elements box to PaddleOCR bboxes, by taking overlapping boxes.
Criterion is iou > max_iou / delta where max_iou is the biggest found overlap.
Boxes are expeceted in format (x0, y0, x1, y1)
Args:
yolox_box (np array [4]): Cached Bbox.
paddle_ocr_boxes (np array... | match_bboxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def join_yolox_graphic_elements_and_paddle_output(yolox_output, paddle_boxes, paddle_txts):
"""
Matching boxes
We need to associate a text to the paddle detections.
For each class and for each CACHED detections, we look for overlapping text bboxes
with IoU > max_iou / delta where max_iou is the big... |
Matching boxes
We need to associate a text to the paddle detections.
For each class and for each CACHED detections, we look for overlapping text bboxes
with IoU > max_iou / delta where max_iou is the biggest found overlap.
Found texts are added to the class representation, and removed from the tex... | join_yolox_graphic_elements_and_paddle_output | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def assign_boxes(paddle_box, boxes, delta=2.0, min_overlap=0.25):
"""
Assigns the closest bounding boxes to a reference `paddle_box` based on overlap.
Args:
paddle_box (list or numpy.ndarray): Reference bounding box [x_min, y_min, x_max, y_max].
boxes (numpy.ndarray): Array of candidate bou... |
Assigns the closest bounding boxes to a reference `paddle_box` based on overlap.
Args:
paddle_box (list or numpy.ndarray): Reference bounding box [x_min, y_min, x_max, y_max].
boxes (numpy.ndarray): Array of candidate bounding boxes with shape (N, 4).
delta (float, optional): Factor fo... | assign_boxes | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def build_markdown(df):
"""
Convert a dataframe into a markdown table.
Args:
df (pandas DataFrame): The dataframe to convert.
Returns:
list[list]: A list of lists representing the markdown table.
"""
df = df.reset_index(drop=True)
n_cols = max([np.max(c) for c in df["col_id... |
Convert a dataframe into a markdown table.
Args:
df (pandas DataFrame): The dataframe to convert.
Returns:
list[list]: A list of lists representing the markdown table.
| build_markdown | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def merge_text_in_cell(df_cell):
"""
Merges text from multiple rows into a single cell and recalculates its bounding box.
Values are sorted by rounded (y, x) coordinates.
Args:
df_cell (pandas.DataFrame): DataFrame containing cells to merge.
Returns:
pandas.DataFrame: Updated DataF... |
Merges text from multiple rows into a single cell and recalculates its bounding box.
Values are sorted by rounded (y, x) coordinates.
Args:
df_cell (pandas.DataFrame): DataFrame containing cells to merge.
Returns:
pandas.DataFrame: Updated DataFrame with merged text and a single bound... | merge_text_in_cell | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def remove_empty_row(mat):
"""
Remove empty rows from a matrix.
Args:
mat (list[list]): The matrix to remove empty rows from.
Returns:
list[list]: The matrix with empty rows removed.
"""
mat_filter = []
for row in mat:
if max([len(c) for c in row]):
mat_... |
Remove empty rows from a matrix.
Args:
mat (list[list]): The matrix to remove empty rows from.
Returns:
list[list]: The matrix with empty rows removed.
| remove_empty_row | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def display_markdown(
data: list[list[str]],
use_header: bool = False,
) -> str:
"""
Convert a list of lists of strings into a markdown table.
Parameters:
data (list[list[str]]): The table data. The first sublist should contain headers.
use_header (bool, optional): Whether to use th... |
Convert a list of lists of strings into a markdown table.
Parameters:
data (list[list[str]]): The table data. The first sublist should contain headers.
use_header (bool, optional): Whether to use the first sublist as headers. Defaults to True.
Returns:
str: A markdown-formatted ta... | display_markdown | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/table_and_chart.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/table_and_chart.py | Apache-2.0 |
def ensure_base64_is_png(base64_image: str) -> str:
"""
Ensures the given base64-encoded image is in PNG format. Converts to PNG if necessary.
Parameters
----------
base64_image : str
Base64-encoded image string.
Returns
-------
str
Base64-encoded PNG image string.
... |
Ensures the given base64-encoded image is in PNG format. Converts to PNG if necessary.
Parameters
----------
base64_image : str
Base64-encoded image string.
Returns
-------
str
Base64-encoded PNG image string.
| ensure_base64_is_png | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def pad_image(
array: np.ndarray,
target_width: int = DEFAULT_MAX_WIDTH,
target_height: int = DEFAULT_MAX_HEIGHT,
background_color: int = 255,
dtype=np.uint8,
) -> Tuple[np.ndarray, Tuple[int, int]]:
"""
Pads a NumPy array representing an image to the specified target dimensions.
If the... |
Pads a NumPy array representing an image to the specified target dimensions.
If the target dimensions are smaller than the image dimensions, no padding will be applied
in that dimension. If the target dimensions are larger, the image will be centered within the
canvas of the specified target size, wit... | pad_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def check_numpy_image_size(image: np.ndarray, min_height: int, min_width: int) -> bool:
"""
Checks if the height and width of the image are larger than the specified minimum values.
Parameters:
image (np.ndarray): The image array (assumed to be in shape (H, W, C) or (H, W)).
min_height (int): The m... |
Checks if the height and width of the image are larger than the specified minimum values.
Parameters:
image (np.ndarray): The image array (assumed to be in shape (H, W, C) or (H, W)).
min_height (int): The minimum height required.
min_width (int): The minimum width required.
Returns:
bool... | check_numpy_image_size | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def crop_image(
array: np.array, bbox: Tuple[int, int, int, int], min_width: int = 1, min_height: int = 1
) -> Optional[np.ndarray]:
"""
Crops a NumPy array representing an image according to the specified bounding box.
Parameters
----------
array : np.array
The image as a NumPy array.
... |
Crops a NumPy array representing an image according to the specified bounding box.
Parameters
----------
array : np.array
The image as a NumPy array.
bbox : Tuple[int, int, int, int]
The bounding box to crop the image to, given as (w1, h1, w2, h2).
min_width : int, optional
... | crop_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def normalize_image(
array: np.ndarray,
r_mean: float = 0.485,
g_mean: float = 0.456,
b_mean: float = 0.406,
r_std: float = 0.229,
g_std: float = 0.224,
b_std: float = 0.225,
) -> np.ndarray:
"""
Normalizes an RGB image by applying a mean and standard deviation to each channel.
... |
Normalizes an RGB image by applying a mean and standard deviation to each channel.
Parameters:
----------
array : np.ndarray
The input image array, which can be either grayscale or RGB. The image should have a shape of
(height, width, 3) for RGB images, or (height, width) or (height, w... | normalize_image | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def numpy_to_base64(array: np.ndarray) -> str:
"""
Converts a NumPy array representing an image to a base64-encoded string.
The function takes a NumPy array, converts it to a PIL image, and then encodes
the image as a PNG in a base64 string format. The input array is expected to be in
a format that... |
Converts a NumPy array representing an image to a base64-encoded string.
The function takes a NumPy array, converts it to a PIL image, and then encodes
the image as a PNG in a base64 string format. The input array is expected to be in
a format that can be converted to a valid image, such as having a s... | numpy_to_base64 | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def base64_to_numpy(base64_string: str) -> np.ndarray:
"""
Convert a base64-encoded image string to a NumPy array.
Parameters
----------
base64_string : str
Base64-encoded string representing an image.
Returns
-------
numpy.ndarray
NumPy array representation of the deco... |
Convert a base64-encoded image string to a NumPy array.
Parameters
----------
base64_string : str
Base64-encoded string representing an image.
Returns
-------
numpy.ndarray
NumPy array representation of the decoded image.
Raises
------
ValueError
If th... | base64_to_numpy | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/image_processing/transforms.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/image_processing/transforms.py | Apache-2.0 |
def configure_logging(logger, level_name):
"""
Parameters:
- level_name (str): The name of the logging level (e.g., "DEBUG", "INFO").
"""
numeric_level = getattr(logging, level_name, None)
if not isinstance(numeric_level, int):
raise ValueError(f"Invalid log level: {level_name}")
l... |
Parameters:
- level_name (str): The name of the logging level (e.g., "DEBUG", "INFO").
| configure_logging | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/logging/configuration.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/logging/configuration.py | Apache-2.0 |
def handle(self):
"""
Handles incoming client requests, validates the request data, and dispatches to the appropriate
command handler.
Raises
------
ValidationError
If the incoming request data fails schema validation.
Exception
If there i... |
Handles incoming client requests, validates the request data, and dispatches to the appropriate
command handler.
Raises
------
ValidationError
If the incoming request data fails schema validation.
Exception
If there is an unexpected error while p... | handle | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _handle_push(
self, data: PushRequestSchema, transaction_id: str, queue: OrderedMessageQueue, queue_lock: threading.Lock
):
"""
Handles a PUSH command to add a message to the specified queue.
Parameters
----------
data : PushRequestSchema
The validate... |
Handles a PUSH command to add a message to the specified queue.
Parameters
----------
data : PushRequestSchema
The validated data for the PUSH command.
transaction_id : str
The unique transaction ID for the operation.
queue : OrderedMessageQueue
... | _handle_push | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _handle_push_for_nv_ingest(
self, data: PushRequestSchema, queue: OrderedMessageQueue, queue_lock: threading.Lock
):
"""
Handles a PUSH_FOR_NV_INGEST command, which includes generating a unique job ID and
updating the message payload accordingly.
Parameters
-----... |
Handles a PUSH_FOR_NV_INGEST command, which includes generating a unique job ID and
updating the message payload accordingly.
Parameters
----------
data : PushRequestSchema
The validated data for the PUSH_FOR_NV_INGEST command.
queue : OrderedMessageQueue
... | _handle_push_for_nv_ingest | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _handle_pop(self, data: PopRequestSchema, queue: OrderedMessageQueue, queue_lock: threading.Lock):
"""
Handles a POP command to retrieve a message from the specified queue.
Parameters
----------
data : PopRequestSchema
The validated data for the POP command.
... |
Handles a POP command to retrieve a message from the specified queue.
Parameters
----------
data : PopRequestSchema
The validated data for the POP command.
queue : OrderedMessageQueue
The queue from which the message will be retrieved.
queue_lock... | _handle_pop | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _size_of_queue(
self, data: SizeRequestSchema, queue: OrderedMessageQueue, queue_lock: threading.Lock
) -> ResponseSchema:
"""
Retrieves the size of the specified queue.
Parameters
----------
data : SizeRequestSchema
The validated data for the SIZE co... |
Retrieves the size of the specified queue.
Parameters
----------
data : SizeRequestSchema
The validated data for the SIZE command.
queue : OrderedMessageQueue
The queue whose size will be queried.
queue_lock : threading.Lock
The lock ... | _size_of_queue | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _wait_for_ack(self, transaction_id: str, timeout: Optional[float]) -> bool:
"""
Waits for an acknowledgment (ACK) from the client for a specific transaction.
Parameters
----------
transaction_id : str
The unique transaction ID for the operation.
timeout :... |
Waits for an acknowledgment (ACK) from the client for a specific transaction.
Parameters
----------
transaction_id : str
The unique transaction ID for the operation.
timeout : float, optional
The timeout period for waiting for the ACK.
Returns
... | _wait_for_ack | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _send_response(self, response: ResponseSchema):
"""
Sends a response back to the client.
Parameters
----------
response : ResponseSchema
The response to send to the client.
Raises
------
Exception
If there is an error while se... |
Sends a response back to the client.
Parameters
----------
response : ResponseSchema
The response to send to the client.
Raises
------
Exception
If there is an error while sending the response.
| _send_response | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _recv_exact(self, num_bytes: int) -> Optional[bytes]:
"""
Receives an exact number of bytes from the client connection.
Parameters
----------
num_bytes : int
The number of bytes to receive.
Returns
-------
Optional[bytes]
The ... |
Receives an exact number of bytes from the client connection.
Parameters
----------
num_bytes : int
The number of bytes to receive.
Returns
-------
Optional[bytes]
The received bytes, or None if the connection is closed.
| _recv_exact | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def __new__(cls, host: str, port: int, max_queue_size: int):
"""
Ensures that only one instance of SimpleMessageBroker is created per host and port combination.
Parameters
----------
host : str
The hostname or IP address for the server.
port : int
... |
Ensures that only one instance of SimpleMessageBroker is created per host and port combination.
Parameters
----------
host : str
The hostname or IP address for the server.
port : int
The port number for the server.
max_queue_size : int
... | __new__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def __init__(self, host: str, port: int, max_queue_size: int):
"""
Initializes the SimpleMessageBroker server, setting up message queues and locks.
Parameters
----------
host : str
The hostname or IP address for the server.
port : int
The port num... |
Initializes the SimpleMessageBroker server, setting up message queues and locks.
Parameters
----------
host : str
The hostname or IP address for the server.
port : int
The port number for the server.
max_queue_size : int
The maximum s... | __init__ | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def _initialize_queue(self, queue_name: str):
"""
Initializes a new message queue with the specified name if it doesn't already exist.
Parameters
----------
queue_name : str
The name of the queue to initialize.
"""
with self.lock:
if queu... |
Initializes a new message queue with the specified name if it doesn't already exist.
Parameters
----------
queue_name : str
The name of the queue to initialize.
| _initialize_queue | python | NVIDIA/nv-ingest | api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | https://github.com/NVIDIA/nv-ingest/blob/master/api/src/nv_ingest_api/util/message_brokers/simple_message_broker/broker.py | Apache-2.0 |
def can_push(self):
"""Check if the queue can accept more messages."""
with self.lock:
return self.maxsize == 0 or (len(self.queue) + len(self.in_flight)) < self.maxsize | Check if the queue can accept more messages. | can_push | 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 push(self, message):
"""Add a message to the queue after it has been acknowledged."""
with self.lock:
index = self.next_index
self.next_index += 1
heapq.heappush(self.queue, (index, message))
self.not_empty.notify()
return index | Add a message to the queue after it has been acknowledged. | push | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.