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 organize_documents_by_type(response_data: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]: """ Organize documents by their content type. This function takes a list of response documents, extracts the content type from each document's metadata, and organizes the documents into a dictionary,...
Organize documents by their content type. This function takes a list of response documents, extracts the content type from each document's metadata, and organizes the documents into a dictionary, where the keys are content types and the values are lists of documents belonging to each type. Parame...
organize_documents_by_type
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 save_response_data(response: Dict[str, Any], output_directory: str, images_to_disk: bool = False) -> None: """ Save the response data into categorized metadata JSON files and optionally save images to disk. This function processes the response data, organizes it based on document types, and saves the o...
Save the response data into categorized metadata JSON files and optionally save images to disk. This function processes the response data, organizes it based on document types, and saves the organized data into a specified output directory as JSON files. If 'images_to_disk' is True and the document type i...
save_response_data
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 get_valid_filename(name: Any) -> str: """ Return a sanitized version of the given filename. This function, adapted from Django (https://github.com/django/django/blob/main/django/utils/text.py), converts the input string to a form that is safe to use as a filename. It trims leading and trailing spac...
Return a sanitized version of the given filename. This function, adapted from Django (https://github.com/django/django/blob/main/django/utils/text.py), converts the input string to a form that is safe to use as a filename. It trims leading and trailing spaces, replaces remaining spaces with underscore...
get_valid_filename
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 configure_logging(logger, log_level: str): """ Configures the logging level based on a log_level string. Parameters ---------- logger: logging.Logger The logger to configure. log_level : str The logging level as a string, expected to be one of 'DEBUG', 'INFO', 'WARNI...
Configures the logging level based on a log_level string. Parameters ---------- logger: logging.Logger The logger to configure. log_level : str The logging level as a string, expected to be one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'.
configure_logging
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/cli/util/system.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/system.py
Apache-2.0
def has_permissions(path: str, read: bool = False, write: bool = False) -> bool: """ Checks if the current user has specified permissions on a path. Parameters ---------- path : str The filesystem path to check permissions on. read : bool, optional Whether to check for read perm...
Checks if the current user has specified permissions on a path. Parameters ---------- path : str The filesystem path to check permissions on. read : bool, optional Whether to check for read permission. write : bool, optional Whether to check for write permission. R...
has_permissions
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/cli/util/system.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/system.py
Apache-2.0
def ensure_directory_with_permissions(directory_path: str): """ Ensures that a directory exists and the current user has read/write permissions. If the directory does not exist, attempts to create it after checking the parent directory for write permission. Parameters ---------- directory_path ...
Ensures that a directory exists and the current user has read/write permissions. If the directory does not exist, attempts to create it after checking the parent directory for write permission. Parameters ---------- directory_path : str The path to the directory to check or create. Re...
ensure_directory_with_permissions
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/cli/util/system.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/cli/util/system.py
Apache-2.0
def _handle_processing_failure(self, job_index: str, error_msg: str, is_submission_failure: bool = False) -> None: """ Handles terminal failures during job initiation or processing. Logs the error, records the failure, cleans up retry counts, and attempts to update the job's state local...
Handles terminal failures during job initiation or processing. Logs the error, records the failure, cleans up retry counts, and attempts to update the job's state locally in the client. This method does not increment the overall processed count itself. Parameters -----...
_handle_processing_failure
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def _handle_processing_success(self, job_index: str, result_data: Dict[str, Any], trace_id: Optional[str]) -> None: """ Handles the successful fetch and retrieval of a job result. Stores the result, cleans up retry counts, and triggers the completion callback if provided. This method do...
Handles the successful fetch and retrieval of a job result. Stores the result, cleans up retry counts, and triggers the completion callback if provided. This method does not increment the overall processed count itself. Parameters ---------- job_index : str ...
_handle_processing_success
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def _log_final_status(self, total_jobs: int) -> None: """ Logs the final processing summary and checks for count discrepancies. Parameters ---------- total_jobs : int The total number of jobs that were initially intended for processing. """ final_proc...
Logs the final processing summary and checks for count discrepancies. Parameters ---------- total_jobs : int The total number of jobs that were initially intended for processing.
_log_final_status
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def __init__( self, message_client_allocator: Type[MessageBrokerClientBase] = RestClient, message_client_hostname: Optional[str] = "localhost", message_client_port: Optional[int] = 7670, message_client_kwargs: Optional[Dict[str, Any]] = None, msg_counter_id: Optional[str]...
Initialize the NvIngestClient. Parameters ---------- message_client_allocator : Type[MessageBrokerClientBase], optional Callable that creates the message broker client. Defaults to RestClient. message_client_hostname : str, optional Hostname of the REST/...
__init__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def __str__(self) -> str: """ Returns a string representation of the NvIngestClient configuration and runtime state. Returns ------- str A string representation of the client showing the Redis configuration. """ info = "NvIngestClient:\n" info...
Returns a string representation of the NvIngestClient configuration and runtime state. Returns ------- str A string representation of the client showing the Redis configuration.
__str__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def _generate_job_index(self) -> str: """ Generates a unique job ID by combining a UUID with an incremented value from Redis. Returns ------- str A unique job ID in the format of "<UUID>_<Redis incremented value>". IF the client is a RedisClient. In the ...
Generates a unique job ID by combining a UUID with an incremented value from Redis. Returns ------- str A unique job ID in the format of "<UUID>_<Redis incremented value>". IF the client is a RedisClient. In the case of a RestClient it is simply the UUID. ...
_generate_job_index
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def _pop_job_state(self, job_index: str) -> JobState: """ Deletes the job with the specified ID from the job tracking dictionary. Parameters ---------- job_index : str The ID of the job to delete. """ job_state = self._get_and_check_job_state(job_ind...
Deletes the job with the specified ID from the job tracking dictionary. Parameters ---------- job_index : str The ID of the job to delete.
_pop_job_state
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def _get_and_check_job_state( self, job_index: str, required_state: Optional[Union[JobStateEnum, List[JobStateEnum]]] = None, ) -> JobState: """ Retrieve and optionally validate the state of a job. Parameters ---------- job_index : str The...
Retrieve and optionally validate the state of a job. Parameters ---------- job_index : str The client-side identifier of the job. required_state : JobStateEnum or list of JobStateEnum, optional State or list of states the job must currently be in. If pro...
_get_and_check_job_state
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def _add_single_job(self, job_spec: JobSpec) -> str: """ Add a single job specification to internal tracking. Parameters ---------- job_spec : JobSpec The specification object describing the job. Returns ------- str The newly gene...
Add a single job specification to internal tracking. Parameters ---------- job_spec : JobSpec The specification object describing the job. Returns ------- str The newly generated job index.
_add_single_job
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def add_job(self, job_spec: Union[BatchJobSpec, JobSpec]) -> Union[str, List[str]]: """ Add one or more jobs to the client for later processing. Parameters ---------- job_spec : JobSpec or BatchJobSpec A single job specification or a batch containing multiple specs. ...
Add one or more jobs to the client for later processing. Parameters ---------- job_spec : JobSpec or BatchJobSpec A single job specification or a batch containing multiple specs. Returns ------- str or list of str The job index for a sin...
add_job
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def create_task( self, job_index: Union[str, int], task_type: TaskType, task_params: Optional[Dict[str, Any]] = None, ) -> None: """ Create and attach a new task to a pending job by type and parameters. Parameters ---------- job_index : str or...
Create and attach a new task to a pending job by type and parameters. Parameters ---------- job_index : str or int Identifier of the job to modify. task_type : TaskType Enum specifying the kind of task to create. task_params : dict, optional ...
create_task
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def fetch_job_result_cli( self, job_ids: Union[str, List[str]], data_only: bool = False, ) -> List[Tuple[Any, str, Optional[str]]]: """ Fetch job results via CLI semantics (synchronous list return). Parameters ---------- job_ids : str or list of str ...
Fetch job results via CLI semantics (synchronous list return). Parameters ---------- job_ids : str or list of str Single or multiple client-side job identifiers. data_only : bool, optional If True, extract only the 'data' field. Default is False. ...
fetch_job_result_cli
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def fetch_job_result_async(self, job_ids: Union[str, List[str]], data_only: bool = True) -> Dict[Future, str]: """ Fetches job results for a list or a single job ID asynchronously and returns a mapping of futures to job IDs. Parameters: job_ids (Union[str, List[str]]): A single job ...
Fetches job results for a list or a single job ID asynchronously and returns a mapping of futures to job IDs. Parameters: job_ids (Union[str, List[str]]): A single job ID or a list of job IDs. timeout (float): Timeout (connect, read) for fetching each job result, in seconds. ...
fetch_job_result_async
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/client.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/client.py
Apache-2.0
def ensure_job_specs(func): """Decorator to ensure _job_specs is initialized before calling task methods.""" @wraps(func) def wrapper(self, *args, **kwargs): if self._job_specs is None: raise ValueError( "Job specifications are not initialized because some files are " ...
Decorator to ensure _job_specs is initialized before calling task methods.
ensure_job_specs
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def _create_client(self, **kwargs) -> None: """ Creates an instance of NvIngestClient if `_client` is not set. Raises ------ ValueError If `_client` already exists. """ if self._client is not None: raise ValueError("self._client already ex...
Creates an instance of NvIngestClient if `_client` is not set. Raises ------ ValueError If `_client` already exists.
_create_client
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def files(self, documents: Union[str, List[str]]) -> "Ingestor": """ Add documents (local paths, globs, or remote URIs) for processing. Remote URIs will force `_all_local=False`. Local globs that match nothing are fine. Explicit local paths that don't exist cause `_all_local=Fal...
Add documents (local paths, globs, or remote URIs) for processing. Remote URIs will force `_all_local=False`. Local globs that match nothing are fine. Explicit local paths that don't exist cause `_all_local=False`.
files
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def load(self, **kwargs) -> "Ingestor": """ Ensure all document files are accessible locally, downloading if necessary. For each document in `_documents`, checks if the file exists locally. If not, attempts to download the file to a temporary directory using `fsspec`. Updates `_...
Ensure all document files are accessible locally, downloading if necessary. For each document in `_documents`, checks if the file exists locally. If not, attempts to download the file to a temporary directory using `fsspec`. Updates `_documents` with paths to local copies, initializes ...
load
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def all_tasks(self) -> "Ingestor": """ Adds a default set of tasks to the batch job specification. The default tasks include extracting text, tables, charts, images, deduplication, filtering, splitting, and embedding tasks. Returns ------- Ingestor R...
Adds a default set of tasks to the batch job specification. The default tasks include extracting text, tables, charts, images, deduplication, filtering, splitting, and embedding tasks. Returns ------- Ingestor Returns self for chaining.
all_tasks
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def dedup(self, **kwargs: Any) -> "Ingestor": """ Adds a DedupTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the DedupTask. Returns ------- Ingestor Returns self for chaining. ...
Adds a DedupTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the DedupTask. Returns ------- Ingestor Returns self for chaining.
dedup
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def embed(self, **kwargs: Any) -> "Ingestor": """ Adds an EmbedTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the EmbedTask. Returns ------- Ingestor Returns self for chaining. ...
Adds an EmbedTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the EmbedTask. Returns ------- Ingestor Returns self for chaining.
embed
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def extract(self, **kwargs: Any) -> "Ingestor": """ Adds an ExtractTask for each document type to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the ExtractTask. Returns ------- Ingestor Re...
Adds an ExtractTask for each document type to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the ExtractTask. Returns ------- Ingestor Returns self for chaining.
extract
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def filter(self, **kwargs: Any) -> "Ingestor": """ Adds a FilterTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the FilterTask. Returns ------- Ingestor Returns self for chaining. ...
Adds a FilterTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the FilterTask. Returns ------- Ingestor Returns self for chaining.
filter
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def split(self, **kwargs: Any) -> "Ingestor": """ Adds a SplitTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the SplitTask. Returns ------- Ingestor Returns self for chaining. ...
Adds a SplitTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the SplitTask. Returns ------- Ingestor Returns self for chaining.
split
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def store(self, **kwargs: Any) -> "Ingestor": """ Adds a StoreTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the StoreTask. Returns ------- Ingestor Returns self for chaining. ...
Adds a StoreTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the StoreTask. Returns ------- Ingestor Returns self for chaining.
store
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def caption(self, **kwargs: Any) -> "Ingestor": """ Adds a CaptionTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the CaptionTask. Returns ------- Ingestor Returns self for chaining....
Adds a CaptionTask to the batch job specification. Parameters ---------- kwargs : dict Parameters specific to the CaptionTask. Returns ------- Ingestor Returns self for chaining.
caption
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def _count_job_states(self, job_states: set[JobStateEnum]) -> int: """ Counts the jobs in specified states. Parameters ---------- job_states : set Set of JobStateEnum states to count. Returns ------- int Count of jobs in specified...
Counts the jobs in specified states. Parameters ---------- job_states : set Set of JobStateEnum states to count. Returns ------- int Count of jobs in specified states.
_count_job_states
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def remaining_jobs(self) -> int: """ Counts the jobs that are not in a terminal state. Returns ------- int Number of jobs that are neither completed, failed, nor cancelled. """ terminal_jobs = self.completed_jobs() + self.failed_jobs() + self.cancelle...
Counts the jobs that are not in a terminal state. Returns ------- int Number of jobs that are neither completed, failed, nor cancelled.
remaining_jobs
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/client/interface.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/client/interface.py
Apache-2.0
def to_dict(self) -> Dict: """ Converts the job specification instance into a dictionary suitable for JSON serialization. Returns ------- Dict A dictionary representation of the job specification. """ return { "job_payload": { ...
Converts the job specification instance into a dictionary suitable for JSON serialization. Returns ------- Dict A dictionary representation of the job specification.
to_dict
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def add_task(self, task) -> None: """ Adds a task to the job specification. Parameters ---------- task The task to add to the job specification. Assumes the task has a to_dict method. Raises ------ ValueError If the task does not ...
Adds a task to the job specification. Parameters ---------- task The task to add to the job specification. Assumes the task has a to_dict method. Raises ------ ValueError If the task does not have a to_dict method.
add_task
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def __init__(self, job_specs_or_files: Optional[Union[List[JobSpec], List[str]]] = None) -> None: """ Initializes the BatchJobSpec instance. Parameters ---------- job_specs_or_files : Optional[Union[List[JobSpec], List[str]]], optional A list of either `JobSpec` inst...
Initializes the BatchJobSpec instance. Parameters ---------- job_specs_or_files : Optional[Union[List[JobSpec], List[str]]], optional A list of either `JobSpec` instances or file paths. If provided, the instance will be initialized with the corresponding job spe...
__init__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def from_job_specs(self, job_specs: Union[JobSpec, List[JobSpec]]) -> None: """ Initializes the batch with a list of `JobSpec` instances. Parameters ---------- job_specs : Union[JobSpec, List[JobSpec]] A single `JobSpec` or a list of `JobSpec` instances to add to the...
Initializes the batch with a list of `JobSpec` instances. Parameters ---------- job_specs : Union[JobSpec, List[JobSpec]] A single `JobSpec` or a list of `JobSpec` instances to add to the batch.
from_job_specs
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def from_files(self, files: Union[str, List[str]]) -> None: """ Initializes the batch by generating job specifications from file paths. Parameters ---------- files : Union[str, List[str]] A single file path or a list of file paths to create job specifications from. ...
Initializes the batch by generating job specifications from file paths. Parameters ---------- files : Union[str, List[str]] A single file path or a list of file paths to create job specifications from.
from_files
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def _from_dataset(self, dataset: str, shuffle_dataset: bool = True) -> None: """ Internal method to initialize the batch from a dataset. Parameters ---------- dataset : str The path to the dataset file. shuffle_dataset : bool, optional Whether to ...
Internal method to initialize the batch from a dataset. Parameters ---------- dataset : str The path to the dataset file. shuffle_dataset : bool, optional Whether to shuffle the dataset files before adding them to the batch, by default True.
_from_dataset
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def from_dataset(cls, dataset: str, shuffle_dataset: bool = True): """ Class method to create a `BatchJobSpec` instance from a dataset. Parameters ---------- dataset : str The path to the dataset file. shuffle_dataset : bool, optional Whether to s...
Class method to create a `BatchJobSpec` instance from a dataset. Parameters ---------- dataset : str The path to the dataset file. shuffle_dataset : bool, optional Whether to shuffle the dataset files before adding them to the batch, by default True. ...
from_dataset
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def to_dict(self) -> Dict[str, List[Dict]]: """ Serializes the batch of job specifications into a list of dictionaries. Returns ------- List[Dict] A list of dictionaries representing the job specifications in the batch. """ return { file_t...
Serializes the batch of job specifications into a list of dictionaries. Returns ------- List[Dict] A list of dictionaries representing the job specifications in the batch.
to_dict
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def __str__(self) -> str: """ Returns a string representation of the batch. Returns ------- str A string representation of the job specifications in the batch. """ result = "" for file_type, job_specs in self._file_type_to_job_spec.items(): ...
Returns a string representation of the batch. Returns ------- str A string representation of the job specifications in the batch.
__str__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_spec.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_spec.py
Apache-2.0
def job_spec(self, value: JobSpec) -> None: """Sets the job specification associated with the state.""" if self._state not in _PREFLIGHT_STATES: err_msg = f"Attempt to change job_spec after job submission: {self._state.name}" logger.error(err_msg) raise ValueError(er...
Sets the job specification associated with the state.
job_spec
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_state.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_state.py
Apache-2.0
def state(self, value: JobStateEnum) -> None: """Sets the current state of the job with transition constraints.""" if self._state in _TERMINAL_STATES: logger.error(f"Attempt to change state from {self._state.name} to {value.name} denied.") raise ValueError(f"Cannot change state f...
Sets the current state of the job with transition constraints.
state
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/jobs/job_state.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/jobs/job_state.py
Apache-2.0
def __str__(self) -> str: """ Returns a string with the object's config and run time state """ info = "" info += "Audio Extraction Task:\n" if self._auth_token: info += " auth_token: [redacted]\n" if self._grpc_endpoint: info += f" grpc_...
Returns a string with the object's config and run time state
__str__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/audio_extraction.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/audio_extraction.py
Apache-2.0
def to_dict(self) -> Dict: """ Convert to a dict for submission to redis """ task_properties = {} if self._auth_token: task_properties["auth_token"] = self._auth_token if self._grpc_endpoint: task_properties["grpc_endpoint"] = self._grpc_endpoint...
Convert to a dict for submission to redis
to_dict
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/audio_extraction.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/audio_extraction.py
Apache-2.0
def handle_deprecated_fields(cls: Type["EmbedTaskSchema"], values: Dict[str, Any]) -> Dict[str, Any]: """ Handle deprecated fields before model validation. This validator checks for the presence of deprecated keys ('text' and 'tables') in the input dictionary and removes them. Warnings ...
Handle deprecated fields before model validation. This validator checks for the presence of deprecated keys ('text' and 'tables') in the input dictionary and removes them. Warnings are issued if these keys are found. Parameters ---------- values : Dict[str, Any] ...
handle_deprecated_fields
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/embed.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/embed.py
Apache-2.0
def __init__( self, endpoint_url: Optional[str] = None, embedding_model: Optional[str] = None, api_key: Optional[str] = None, text: Optional[bool] = None, tables: Optional[bool] = None, filter_errors: bool = False, ) -> None: """ Initialize the...
Initialize the EmbedTask configuration. Parameters ---------- endpoint_url : Optional[str], optional URL of the embedding endpoint. Defaults to None. embedding_model : Optional[str], optional Name of the embedding model. Defaults to None. api_key...
__init__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/embed.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/embed.py
Apache-2.0
def __str__(self) -> str: """ Return the string representation of the EmbedTask. The string includes the endpoint URL, model name, a redacted API key, and the error filtering flag. Returns ------- str A string representation of the EmbedTask configuration. ...
Return the string representation of the EmbedTask. The string includes the endpoint URL, model name, a redacted API key, and the error filtering flag. Returns ------- str A string representation of the EmbedTask configuration.
__str__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/embed.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/embed.py
Apache-2.0
def to_dict(self) -> Dict[str, Any]: """ Convert the EmbedTask configuration to a dictionary for submission. Returns ------- Dict[str, Any] A dictionary containing the task type and properties, suitable for submission (e.g., to a Redis database). ...
Convert the EmbedTask configuration to a dictionary for submission. Returns ------- Dict[str, Any] A dictionary containing the task type and properties, suitable for submission (e.g., to a Redis database).
to_dict
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/embed.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/embed.py
Apache-2.0
def to_dict(self) -> Dict: """ Convert to a dict for submission to redis (fixme) """ extract_params = { "extract_text": self._extract_text, "extract_images": self._extract_images, "extract_tables": self._extract_tables, "extract_images_meth...
Convert to a dict for submission to redis (fixme)
to_dict
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/extract.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/extract.py
Apache-2.0
def task_factory(task_type: Union[TaskType, str], **kwargs) -> Task: """ Factory method for creating tasks based on the provided task type. Parameters ---------- task_type : TaskType The type of the task to create. **kwargs : dict Additional keyword arguments to pass to the task...
Factory method for creating tasks based on the provided task type. Parameters ---------- task_type : TaskType The type of the task to create. **kwargs : dict Additional keyword arguments to pass to the task's constructor. Returns ------- Task An instance of the...
task_factory
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/primitives/tasks/task_factory.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/primitives/tasks/task_factory.py
Apache-2.0
def get_dataset_statistics(dataset_bytes: BytesIO) -> str: """ Reads a dataset specification from a BytesIO object, computes statistics about the dataset, and returns a formatted string. Parameters ---------- dataset_bytes : BytesIO The BytesIO object containing the dataset in JSON form...
Reads a dataset specification from a BytesIO object, computes statistics about the dataset, and returns a formatted string. Parameters ---------- dataset_bytes : BytesIO The BytesIO object containing the dataset in JSON format. Returns ------- str A formatted string co...
get_dataset_statistics
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/dataset.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/dataset.py
Apache-2.0
def get_dataset_files(dataset_bytes: BytesIO, shuffle: bool = False) -> list: """ Extracts and optionally shuffles the list of files contained in a dataset. Parameters ---------- dataset_bytes : BytesIO The BytesIO object containing the dataset in JSON format. shuffle : bool, optional ...
Extracts and optionally shuffles the list of files contained in a dataset. Parameters ---------- dataset_bytes : BytesIO The BytesIO object containing the dataset in JSON format. shuffle : bool, optional Whether to shuffle the list of files before returning. Defaults to False. ...
get_dataset_files
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/dataset.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/dataset.py
Apache-2.0
def __init__( self, collection_name: Union[str, Dict] = "nv_ingest_collection", milvus_uri: str = "http://localhost:19530", sparse: bool = False, recreate: bool = True, gpu_index: bool = True, gpu_search: bool = True, dense_dim: int = 2048, minio_e...
Initializes the Milvus operator class with the specified configuration parameters. Args: collection_name (Union[str, Dict], optional): The name of the Milvus collection or a dictionary containing collection configuration. Defaults to "nv_ingest_collection". milvu...
__init__
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def create_nvingest_schema(dense_dim: int = 1024, sparse: bool = False, local_index: bool = False) -> CollectionSchema: """ Creates a schema for the nv-ingest produced data. This is currently setup to follow the default expected schema fields in nv-ingest. You can see more about the declared fields in t...
Creates a schema for the nv-ingest produced data. This is currently setup to follow the default expected schema fields in nv-ingest. You can see more about the declared fields in the `nv_ingest.schemas.vdb_task_sink_schema.build_default_milvus_config` function. This schema should have the fields declar...
create_nvingest_schema
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def create_nvingest_index_params( sparse: bool = False, gpu_index: bool = True, gpu_search: bool = True, local_index: bool = True ) -> IndexParams: """ Creates index params necessary to create an index for a collection. At a minimum, this function will create a dense embedding index but can also create ...
Creates index params necessary to create an index for a collection. At a minimum, this function will create a dense embedding index but can also create a sparse embedding index (BM25) for hybrid search. Parameters ---------- sparse : bool, optional When set to true, this adds a Sparse ...
create_nvingest_index_params
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def create_collection( client: MilvusClient, collection_name: str, schema: CollectionSchema, index_params: IndexParams = None, recreate=True, ): """ Creates a milvus collection with the supplied name and schema. Within that collection, this function ensures that the desired indexes are c...
Creates a milvus collection with the supplied name and schema. Within that collection, this function ensures that the desired indexes are created based on the IndexParams supplied. Parameters ---------- client : MilvusClient Client connected to mivlus instance. collection_name : st...
create_collection
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def create_nvingest_collection( collection_name: str, milvus_uri: str = "http://localhost:19530", sparse: bool = False, recreate: bool = True, gpu_index: bool = True, gpu_search: bool = True, dense_dim: int = 2048, recreate_meta: bool = False, ) -> CollectionSchema: """ Creates a...
Creates a milvus collection with an nv-ingest compatible schema under the target name. Parameters ---------- collection_name : str Name of the collection to be created. milvus_uri : str, Milvus address with http(s) preffix and port. Can also be a file path, to activate ...
create_nvingest_collection
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def _get_index_types(index_params: IndexParams, sparse: bool = False) -> Tuple[str, str]: """ Returns the dense and optional sparse index types from Milvus index_params, handling both old (dict) and new (list) formats. Parameters: index_params: The index parameters object with a _indexes attrib...
Returns the dense and optional sparse index types from Milvus index_params, handling both old (dict) and new (list) formats. Parameters: index_params: The index parameters object with a _indexes attribute. sparse (bool): Whether to look for sparse_index as well. Returns: tuple...
_get_index_types
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def write_records_minio( records, writer: RemoteBulkWriter, sparse_model=None, enable_text: bool = True, enable_charts: bool = True, enable_tables: bool = True, enable_images: bool = True, enable_infographics: bool = True, enable_audio: bool = True, record_func=_record_dict, ...
Writes the supplied records to milvus using the supplied writer. If a sparse model is supplied, it will be used to generate sparse embeddings to allow for hybrid search. Will filter records based on type, depending on what types are enabled via the boolean parameters. If the user sets the log level...
write_records_minio
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def bulk_insert_milvus(collection_name: str, writer: RemoteBulkWriter, milvus_uri: str = "http://localhost:19530"): """ This function initialize the bulk ingest of all minio uploaded records, and checks for milvus task completion. Once the function is complete all records have been uploaded to the milvu...
This function initialize the bulk ingest of all minio uploaded records, and checks for milvus task completion. Once the function is complete all records have been uploaded to the milvus collection. Parameters ---------- collection_name : str Name of the milvus collection. writer : ...
bulk_insert_milvus
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def create_bm25_model( records, enable_text: bool = True, enable_charts: bool = True, enable_tables: bool = True, enable_images: bool = True, enable_infographics: bool = True, enable_audio: bool = True, ) -> BM25EmbeddingFunction: """ This function takes the input records and creates...
This function takes the input records and creates a corpus, factoring in filters (i.e. texts, charts, tables) and fits a BM25 model with that information. If the user sets the log level to info, any time a record fails ingestion, it will be reported to the user. Parameters ---------- r...
create_bm25_model
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def stream_insert_milvus( records, client: MilvusClient, collection_name: str, sparse_model=None, enable_text: bool = True, enable_charts: bool = True, enable_tables: bool = True, enable_images: bool = True, enable_infographics: bool = True, enable_audio: bool = True, record_...
This function takes the input records and creates a corpus, factoring in filters (i.e. texts, charts, tables) and fits a BM25 model with that information. If the user sets the log level to info, any time a record fails ingestion, it will be reported to the user. Parameters ---------- r...
stream_insert_milvus
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def write_to_nvingest_collection( records, collection_name: str, milvus_uri: str = "http://localhost:19530", minio_endpoint: str = "localhost:9000", sparse: bool = True, enable_text: bool = True, enable_charts: bool = True, enable_tables: bool = True, enable_images: bool = True, ...
This function takes the input records and creates a corpus, factoring in filters (i.e. texts, charts, tables) and fits a BM25 model with that information. Parameters ---------- records : List List of chunks with attached metadata collection_name : str Milvus Collection to s...
write_to_nvingest_collection
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def dense_retrieval( queries, collection_name: str, client: MilvusClient, dense_model, top_k: int, dense_field: str = "vector", output_fields: List[str] = ["text"], _filter: str = "", ): """ This function takes the input queries and conducts a dense embedding search against t...
This function takes the input queries and conducts a dense embedding search against the dense vector and return the top_k nearest records in the collection. Parameters ---------- queries : List List of queries collection : Collection Milvus Collection to search against ...
dense_retrieval
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def hybrid_retrieval( queries, collection_name: str, client: MilvusClient, dense_model, sparse_model, top_k: int, dense_field: str = "vector", sparse_field: str = "sparse", output_fields: List[str] = ["text"], gpu_search: bool = True, local_index: bool = False, _filter: s...
This function takes the input queries and conducts a hybrid embedding search against the dense and sparse vectors, returning the top_k nearest records in the collection. Parameters ---------- queries : List List of queries collection : Collection Milvus Collection to search...
hybrid_retrieval
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def nvingest_retrieval( queries, collection_name: str, milvus_uri: str = "http://localhost:19530", top_k: int = 5, hybrid: bool = False, dense_field: str = "vector", sparse_field: str = "sparse", embedding_endpoint=None, sparse_model_filepath: str = "bm25_model.json", model_name:...
This function takes the input queries and conducts a hybrid/dense embedding search against the vectors, returning the top_k nearest records in the collection. Parameters ---------- queries : List List of queries collection : Collection Milvus Collection to search against ...
nvingest_retrieval
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def remove_records(source_name: str, collection_name: str, milvus_uri: str = "http://localhost:19530"): """ This function allows a user to remove chunks associated with an ingested file. Supply the full path of the file you would like to remove and this function will remove all the chunks associated wit...
This function allows a user to remove chunks associated with an ingested file. Supply the full path of the file you would like to remove and this function will remove all the chunks associated with that file in the target collection. Parameters ---------- source_name : str The full fil...
remove_records
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def nv_rerank( query, candidates, reranker_endpoint: str = None, model_name: str = None, nvidia_api_key: str = None, truncate: str = "END", max_batch_size: int = 64, topk: int = 5, ): """ This function allows a user to rerank a set of candidates using the nvidia reranker nim. ...
This function allows a user to rerank a set of candidates using the nvidia reranker nim. Parameters ---------- query : str Query the candidates are supposed to answer. candidates : list List of the candidates to rerank. reranker_endpoint : str The endpoint to the nvidia...
nv_rerank
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def recreate_elements(data): """ This function takes the input data and creates a list of elements with the necessary metadata for ingestion. Parameters ---------- data : List List of chunks with attached metadata Returns ------- List List of elements with metadata....
This function takes the input data and creates a list of elements with the necessary metadata for ingestion. Parameters ---------- data : List List of chunks with attached metadata Returns ------- List List of elements with metadata.
recreate_elements
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def pull_all_milvus( collection_name: str, milvus_uri: str = "http://localhost:19530", write_dir: str = None, batch_size: int = 1000 ): """ This function takes the input collection name and pulls all the records from the collection. It will either return the records as a list of dictionaries or writ...
This function takes the input collection name and pulls all the records from the collection. It will either return the records as a list of dictionaries or write them to a specified directory in JSON format. Parameters ---------- collection_name : str Milvus Collection to query against ...
pull_all_milvus
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def get_embeddings(full_records, embedder, batch_size=256): """ This function takes the input records and creates a list of embeddings. The default batch size is 256, but this can be adjusted based on the available resources, to a maximum of 259. This is set by the NVIDIA embedding microservice. ...
This function takes the input records and creates a list of embeddings. The default batch size is 256, but this can be adjusted based on the available resources, to a maximum of 259. This is set by the NVIDIA embedding microservice.
get_embeddings
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def embed_index_collection( data, collection_name, batch_size: int = 256, embedding_endpoint: str = None, model_name: str = None, nvidia_api_key: str = None, milvus_uri: str = "http://localhost:19530", sparse: bool = False, recreate: bool = True, gpu_index: bool = True, gpu_s...
This function takes the input data and creates a collection in Milvus, it will embed the records using the NVIDIA embedding model and store them in the collection. After embedding the records, it will run the same ingestion process as the vdb_upload stage in the Ingestor pipeline. Args: da...
embed_index_collection
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def reindex_collection( current_collection_name: str, new_collection_name: str = None, write_dir: str = None, embedding_endpoint: str = None, model_name: str = None, nvidia_api_key: str = None, milvus_uri: str = "http://localhost:19530", sparse: bool = False, recreate: bool = True, ...
This function will reindex a collection in Milvus. It will pull all the records from the current collection, embed them using the NVIDIA embedding model, and store them in a new collection. After embedding the records, it will run the same ingestion process as the vdb_upload stage in the Ingestor pipel...
reindex_collection
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def reconstruct_pages(anchor_record, records_list, page_signum: int = 0): """ This function allows a user reconstruct the pages for a retrieved chunk. Parameters ---------- anchor_record : dict Query the candidates are supposed to answer. records_list : list List of the candidat...
This function allows a user reconstruct the pages for a retrieved chunk. Parameters ---------- anchor_record : dict Query the candidates are supposed to answer. records_list : list List of the candidates to rerank. page_signum : int The endpoint to the nvidia reranker ...
reconstruct_pages
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/milvus.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/milvus.py
Apache-2.0
def handle_future_result( future: concurrent.futures.Future, timeout=10, ) -> Tuple[Dict[str, Any], str]: """ Handle the result of a completed future job and process annotations. This function processes the result of a future, extracts annotations (if any), logs them, and checks the validity of...
Handle the result of a completed future job and process annotations. This function processes the result of a future, extracts annotations (if any), logs them, and checks the validity of the ingest result. If the result indicates a failure, a `RuntimeError` is raised with a description of the failure. ...
handle_future_result
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/processing.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/processing.py
Apache-2.0
def highlight_error_in_original(original_str: str, task_name: str, error_detail: Dict[str, Any]) -> str: """ Highlights the error-causing text in the original JSON string based on the error type. This function identifies the problematic portion of the JSON string by inspecting the provided error detail...
Highlights the error-causing text in the original JSON string based on the error type. This function identifies the problematic portion of the JSON string by inspecting the provided error details. For errors due to extra fields, it highlights the extra field (using blue and bold formatting). For error...
highlight_error_in_original
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/processing.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/processing.py
Apache-2.0
def format_validation_error(e: ValidationError, task_id: str, original_str: str) -> str: """ Formats validation errors with appropriate highlights and returns a detailed error message. Parameters ---------- e : ValidationError The validation error raised by the schema. task_id : str ...
Formats validation errors with appropriate highlights and returns a detailed error message. Parameters ---------- e : ValidationError The validation error raised by the schema. task_id : str The identifier of the task for which the error occurred. original_str : str The...
format_validation_error
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/processing.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/processing.py
Apache-2.0
def check_schema(schema: Type[BaseModel], options: dict, task_id: str, original_str: str) -> BaseModel: """ Validates the provided options against the given schema and returns a schema instance. Parameters ---------- schema : Type[BaseModel] A Pydantic model class used for validating the op...
Validates the provided options against the given schema and returns a schema instance. Parameters ---------- schema : Type[BaseModel] A Pydantic model class used for validating the options. options : dict The options dictionary to validate. task_id : str The identifier ...
check_schema
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/processing.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/processing.py
Apache-2.0
def main(json_files, output_file): """ Process multiple JSON files, combine and sort entries, and generate a single blob file. JSON_FILES: One or more JSON files to process. """ click.echo(f"Processing {len(json_files)} JSON files...") all_entries = [] try: # Read and collect entri...
Process multiple JSON files, combine and sort entries, and generate a single blob file. JSON_FILES: One or more JSON files to process.
main
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/process_json_files.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/process_json_files.py
Apache-2.0
def count_pages_for_text(file_path: str) -> int: """ Estimates the page count for text files based on word count, using the detect_encoding_and_read_text_file function for reading. """ try: with open(file_path, "rb") as file: # Open file in binary mode file_stream = BytesIO(file...
Estimates the page count for text files based on word count, using the detect_encoding_and_read_text_file function for reading.
count_pages_for_text
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/util.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/util.py
Apache-2.0
def _process_file(file_path: str): """ Synchronously processes a single file, extracting its content and collecting file details. This function serves as a high-level interface for file processing, invoking content extraction and aggregating the results along with file metadata. It is designed to work ...
Synchronously processes a single file, extracting its content and collecting file details. This function serves as a high-level interface for file processing, invoking content extraction and aggregating the results along with file metadata. It is designed to work within a larger processing pipeline, p...
_process_file
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/util.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/util.py
Apache-2.0
def load_data_from_path(path: str) -> Dict: """ Loads data from a specified file path, preparing it for processing. Parameters ---------- path : str The path to the file from which data should be loaded. Returns ------- dict A dictionary containing keys 'file_name', 'id...
Loads data from a specified file path, preparing it for processing. Parameters ---------- path : str The path to the file from which data should be loaded. Returns ------- dict A dictionary containing keys 'file_name', 'id', 'content', and 'document_type', each of ...
load_data_from_path
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/util.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/util.py
Apache-2.0
def generate_matching_files(file_sources): """ Generates a list of file paths that match the given patterns specified in file_sources. Parameters ---------- file_sources : list of str A list containing the file source patterns to match against. Returns ------- generator ...
Generates a list of file paths that match the given patterns specified in file_sources. Parameters ---------- file_sources : list of str A list containing the file source patterns to match against. Returns ------- generator A generator yielding paths to files that match th...
generate_matching_files
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/util.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/util.py
Apache-2.0
def filter_function_kwargs(func, **kwargs): """ Filters and returns keyword arguments that match the parameters of a given function. This function inspects the signature of `func` and extracts any keyword arguments from `kwargs` that correspond to the function's parameters. It returns a dictionary ...
Filters and returns keyword arguments that match the parameters of a given function. This function inspects the signature of `func` and extracts any keyword arguments from `kwargs` that correspond to the function's parameters. It returns a dictionary containing only those arguments that `func` accepts...
filter_function_kwargs
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/util.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/util.py
Apache-2.0
def get_content(results: List[any]): """ Extracts the text and table text content from the results of an NV-Ingest python client job Parameters ---------- results: List[Any] The results of NV-Ingest python client job that contains the desired text and table content Returns ------- ...
Extracts the text and table text content from the results of an NV-Ingest python client job Parameters ---------- results: List[Any] The results of NV-Ingest python client job that contains the desired text and table content Returns ------- Dict A dictionary containing the...
get_content
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/util.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/util.py
Apache-2.0
async def fetch(self, sem, trace_id: str, url: str) -> Dict[str, str]: """ Perform a GET request to the given URL with retry logic for 404 status codes. :param url: URL to make the GET request to. :param sem: Semaphore to ensure only X concurrent requests are in flight :param tr...
Perform a GET request to the given URL with retry logic for 404 status codes. :param url: URL to make the GET request to. :param sem: Semaphore to ensure only X concurrent requests are in flight :param trace_id: The trace_id for the request :param url: The complete URL for the ...
fetch
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/zipkin.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/zipkin.py
Apache-2.0
def get_or_infer_file_type(file_path: str) -> DocumentTypeEnum: """ Determines the file type by inspecting its extension and optionally falls back to MIME type detection if the extension is not recognized. Parameters ---------- file_path : str The path to the file. Returns ----...
Determines the file type by inspecting its extension and optionally falls back to MIME type detection if the extension is not recognized. Parameters ---------- file_path : str The path to the file. Returns ------- DocumentTypeEnum An enum value representing the detecte...
get_or_infer_file_type
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/file_processing/extract.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/file_processing/extract.py
Apache-2.0
def serialize_to_base64(file_stream: BytesIO) -> str: """Reads a PDF file from a BytesIO object and encodes it in base64.""" try: content = base64.b64encode(file_stream.read()).decode("utf-8") return content except IOError: logger.error("Failed to read PDF file from BytesIO object") ...
Reads a PDF file from a BytesIO object and encodes it in base64.
serialize_to_base64
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/file_processing/extract.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/file_processing/extract.py
Apache-2.0
def detect_encoding_and_read_text_file(file_stream: BytesIO) -> str: """Detects encoding and reads a text file from a BytesIO object accordingly.""" try: raw_data = file_stream.read() result = charset_normalizer.detect(raw_data) encoding = result.get("encoding", "utf-8") # Fallback to u...
Detects encoding and reads a text file from a BytesIO object accordingly.
detect_encoding_and_read_text_file
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/file_processing/extract.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/file_processing/extract.py
Apache-2.0
def extract_file_content(path: str) -> Tuple[str, DocumentTypeEnum]: """Extracts content from a file, supporting different formats.""" document_type = get_or_infer_file_type(path) with open(path, "rb") as file: file_stream = BytesIO(file.read()) try: if document_type in [ D...
Extracts content from a file, supporting different formats.
extract_file_content
python
NVIDIA/nv-ingest
client/src/nv_ingest_client/util/file_processing/extract.py
https://github.com/NVIDIA/nv-ingest/blob/master/client/src/nv_ingest_client/util/file_processing/extract.py
Apache-2.0
def run_ingestor(): """ Set up and run the ingestion process to send traffic against the pipeline. """ logger.info("Setting up Ingestor client...") client = NvIngestClient( message_client_allocator=SimpleClient, message_client_port=7671, message_client_hostname="localhost" ) ingesto...
Set up and run the ingestion process to send traffic against the pipeline.
run_ingestor
python
NVIDIA/nv-ingest
examples/launch_libmode_and_run_ingestor.py
https://github.com/NVIDIA/nv-ingest/blob/master/examples/launch_libmode_and_run_ingestor.py
Apache-2.0
def cli( ingest_config_path, edge_buffer_size, num_threads, mode, log_level, ): """ Command line interface for configuring and running the pipeline with specified options. """ # Convert log level from string to logging level log_level_mapping = { "DEBUG": logging.DEBUG, ...
Command line interface for configuring and running the pipeline with specified options.
cli
python
NVIDIA/nv-ingest
src/microservice_entrypoint.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/microservice_entrypoint.py
Apache-2.0
async def _get_ingest_service() -> IngestServiceMeta: """ Gather the appropriate Ingestion Service to use for the nv-ingest endpoint. """ logger.debug("Creating RedisIngestService singleton for dependency injection") return RedisIngestService.get_instance()
Gather the appropriate Ingestion Service to use for the nv-ingest endpoint.
_get_ingest_service
python
NVIDIA/nv-ingest
src/nv_ingest/api/v1/ingest.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/nv_ingest/api/v1/ingest.py
Apache-2.0
async def submit_job_curl_friendly(ingest_service: INGEST_SERVICE_T, file: UploadFile = File(...)): """ A multipart/form-data friendly Job submission endpoint that makes interacting with the nv-ingest service through tools like Curl easier. """ try: file_stream = BytesIO(file.file.read()) ...
A multipart/form-data friendly Job submission endpoint that makes interacting with the nv-ingest service through tools like Curl easier.
submit_job_curl_friendly
python
NVIDIA/nv-ingest
src/nv_ingest/api/v1/ingest.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/nv_ingest/api/v1/ingest.py
Apache-2.0
def trace_id_to_uuid(trace_id: str) -> str: """Convert a 32-character OpenTelemetry trace ID to a UUID-like format.""" trace_id = str(trace.format_trace_id(trace_id)) if len(trace_id) != 32: raise ValueError("Trace ID must be a 32-character hexadecimal string") return f"{trace_id[:8]}-{trace_id[...
Convert a 32-character OpenTelemetry trace ID to a UUID-like format.
trace_id_to_uuid
python
NVIDIA/nv-ingest
src/nv_ingest/api/v1/ingest.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/nv_ingest/api/v1/ingest.py
Apache-2.0
async def fetch_job(job_id: str, ingest_service: INGEST_SERVICE_T): """ Fetches job result, checking job state *before* attempting data retrieval. Distinguishes non-existent jobs (404) from expired results (410). """ current_state: Optional[str] = None try: # Step 1: Get Job State ...
Fetches job result, checking job state *before* attempting data retrieval. Distinguishes non-existent jobs (404) from expired results (410).
fetch_job
python
NVIDIA/nv-ingest
src/nv_ingest/api/v1/ingest.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/nv_ingest/api/v1/ingest.py
Apache-2.0
def extract_data_frame(message: IngestControlMessage) -> Tuple[Any, Dict[str, Any]]: """ Extracts a DataFrame from a message payload and returns it along with a filtered dictionary of required columns. Parameters ---------- message : IngestControlMessage The message object containing the pa...
Extracts a DataFrame from a message payload and returns it along with a filtered dictionary of required columns. Parameters ---------- message : IngestControlMessage The message object containing the payload. Returns ------- Tuple[Any, Dict[str, Any]] A tuple containing th...
extract_data_frame
python
NVIDIA/nv-ingest
src/nv_ingest/framework/orchestration/morpheus/modules/sinks/message_broker_task_sink.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/nv_ingest/framework/orchestration/morpheus/modules/sinks/message_broker_task_sink.py
Apache-2.0
def create_json_payload(message: IngestControlMessage, df_json: Dict[str, Any]) -> List[Dict[str, Any]]: """ Creates JSON payloads based on message status and data. If the size of df_json exceeds 256 MB, splits it into multiple fragments, each less than 256 MB. Adds optional trace and annotation data to the...
Creates JSON payloads based on message status and data. If the size of df_json exceeds 256 MB, splits it into multiple fragments, each less than 256 MB. Adds optional trace and annotation data to the first fragment.
create_json_payload
python
NVIDIA/nv-ingest
src/nv_ingest/framework/orchestration/morpheus/modules/sinks/message_broker_task_sink.py
https://github.com/NVIDIA/nv-ingest/blob/master/src/nv_ingest/framework/orchestration/morpheus/modules/sinks/message_broker_task_sink.py
Apache-2.0