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 load_model( model_uri: str, dst_path: Optional[str] = None, return_type="pipeline", device=None, **kwargs ): """ Load a ``transformers`` object from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/loca...
Load a ``transformers`` object from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs...
load_model
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def persist_pretrained_model(model_uri: str) -> None: """ Persist Transformers pretrained model weights to the artifacts directory of the specified model_uri. This API is primary used for updating an MLflow Model that was logged or saved with setting save_pretrained=False. Such models cannot be register...
Persist Transformers pretrained model weights to the artifacts directory of the specified model_uri. This API is primary used for updating an MLflow Model that was logged or saved with setting save_pretrained=False. Such models cannot be registered to Databricks Workspace Model Registry, due to the ful...
persist_pretrained_model
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _is_model_distributed_in_memory(transformers_model): """Check if the model is distributed across multiple devices in memory.""" # Check if the model attribute exists. If not, accelerate was not used and the model can # be safely saved if not hasattr(transformers_model, "hf_device_map"): ret...
Check if the model is distributed across multiple devices in memory.
_is_model_distributed_in_memory
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _load_model(path: str, flavor_config, return_type: str, device=None, **kwargs): """ Loads components from a locally serialized ``Pipeline`` object. """ import transformers conf = { "task": flavor_config[FlavorKey.TASK], } if framework := flavor_config.get(FlavorKey.FRAMEWORK): ...
Loads components from a locally serialized ``Pipeline`` object.
_load_model
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _fetch_model_card(model_name): """ Attempts to retrieve the model card for the specified model architecture iff the `huggingface_hub` library is installed. If a card cannot be found in the registry or the library is not installed, returns None. """ try: import huggingface_hub as hub ...
Attempts to retrieve the model card for the specified model architecture iff the `huggingface_hub` library is installed. If a card cannot be found in the registry or the library is not installed, returns None.
_fetch_model_card
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _write_card_data(card_data, path): """ Writes the card data, if specified or available, to the provided path in two separate files """ if card_data: try: path.joinpath(_CARD_TEXT_FILE_NAME).write_text(card_data.text, encoding="utf-8") except UnicodeError as e: ...
Writes the card data, if specified or available, to the provided path in two separate files
_write_card_data
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _extract_license_file_from_repository(model_name): """Returns the top-level file inventory of `RepoFile` objects from the huggingface hub""" try: import huggingface_hub as hub except ImportError: _logger.debug( f"Unable to list repository contents for the model repo {model_na...
Returns the top-level file inventory of `RepoFile` objects from the huggingface hub
_extract_license_file_from_repository
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _get_supported_pretrained_model_types(): """ Users might not have all the necessary libraries installed to determine the supported model """ supported_model_types = () try: from transformers import FlaxPreTrainedModel supported_model_types += (FlaxPreTrainedModel,) except ...
Users might not have all the necessary libraries installed to determine the supported model
_get_supported_pretrained_model_types
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _build_pipeline_from_model_input(model_dict: dict[str, Any], task: Optional[str]) -> Pipeline: """ Utility for generating a pipeline from component parts. If required components are not specified, use the transformers library pipeline component validation to force raising an exception. The underlyin...
Utility for generating a pipeline from component parts. If required components are not specified, use the transformers library pipeline component validation to force raising an exception. The underlying Exception thrown in transformers is verbose enough for diagnosis.
_build_pipeline_from_model_input
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _get_task_for_model(model_name_or_path: str, default_task=None) -> str: """ Get the Transformers pipeline task type fro the model instance. NB: The get_task() function only works for remote models available in the Hugging Face hub, so the default task should be supplied when using a custom local mo...
Get the Transformers pipeline task type fro the model instance. NB: The get_task() function only works for remote models available in the Hugging Face hub, so the default task should be supplied when using a custom local model.
_get_task_for_model
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _validate_llm_inference_task_type(llm_inference_task: str, pipeline_task: str) -> None: """ Validates that an ``inference_task`` type is supported by ``transformers`` pipeline type. """ supported_llm_inference_tasks = _SUPPORTED_LLM_INFERENCE_TASK_TYPES_BY_PIPELINE_TASK.get( pipeline_task, [...
Validates that an ``inference_task`` type is supported by ``transformers`` pipeline type.
_validate_llm_inference_task_type
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _get_engine_type(model): """ Determines the underlying execution engine for the model based on the 3 currently supported deep learning framework backends: ``tensorflow``, ``torch``, or ``flax``. """ from transformers import FlaxPreTrainedModel, PreTrainedModel, TFPreTrainedModel from transfo...
Determines the underlying execution engine for the model based on the 3 currently supported deep learning framework backends: ``tensorflow``, ``torch``, or ``flax``.
_get_engine_type
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _get_model_config(local_path, pyfunc_config): """ Load the model configuration if it was provided for use in the `_TransformersWrapper` pyfunc Model wrapper. """ config_path = local_path.joinpath("inference_config.txt") if config_path.exists(): _logger.warning( "Inference...
Load the model configuration if it was provided for use in the `_TransformersWrapper` pyfunc Model wrapper.
_get_model_config
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _load_pyfunc(path, model_config: Optional[dict[str, Any]] = None): """ Loads the model as pyfunc model """ local_path = pathlib.Path(path) flavor_configuration = _get_flavor_configuration(local_path, FLAVOR_NAME) model_config = _get_model_config(local_path.joinpath(_COMPONENTS_BINARY_DIR_NAM...
Loads the model as pyfunc model
_load_pyfunc
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _is_conversational_pipeline(pipeline): """ Checks if the pipeline is a ConversationalPipeline. """ if cp := _try_import_conversational_pipeline(): return isinstance(pipeline, cp) return False
Checks if the pipeline is a ConversationalPipeline.
_is_conversational_pipeline
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _try_import_conversational_pipeline(): """ Try importing ConversationalPipeline because for version > 4.41.2 it is removed from the transformers package. """ try: from transformers import ConversationalPipeline return ConversationalPipeline except ImportError: return
Try importing ConversationalPipeline because for version > 4.41.2 it is removed from the transformers package.
_try_import_conversational_pipeline
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_raw_pipeline_input(self, data): """ Converts inputs to the expected types for specific Pipeline types. Specific logic for individual pipeline types are called via their respective methods if the input isn't a basic str or List[str] input type of Pipeline. These parsers...
Converts inputs to the expected types for specific Pipeline types. Specific logic for individual pipeline types are called via their respective methods if the input isn't a basic str or List[str] input type of Pipeline. These parsers are required due to the conversion that occurs within...
_parse_raw_pipeline_input
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _validate_text_classification_input(data): """ Perform input type validation for TextClassification pipelines and casting of data that is manipulated internally by the MLflow model server back to a structure that can be used for pipeline inference. To illustrate the input an...
Perform input type validation for TextClassification pipelines and casting of data that is manipulated internally by the MLflow model server back to a structure that can be used for pipeline inference. To illustrate the input and outputs of this function, for the following inputs to ...
_validate_text_classification_input
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _check_keys(payload): """Check if a dictionary contains only allowable keys.""" allowable_str_keys = {"text", "text_pair"} if set(payload) - allowable_str_keys and not all( isinstance(key, int) for key in payload.keys() ): raise MlflowE...
Check if a dictionary contains only allowable keys.
_check_keys
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _coerce_exploded_dict_to_single_dict( self, data: list[dict[str, Any]] ) -> dict[str, list[Any]]: """ Parses the result of Pandas DataFrame.to_dict(orient="records") from pyfunc signature validation to coerce the output to the required format for a Pipeline that requires ...
Parses the result of Pandas DataFrame.to_dict(orient="records") from pyfunc signature validation to coerce the output to the required format for a Pipeline that requires a single dict with list elements such as TableQuestionAnsweringPipeline. Example input: [ ...
_coerce_exploded_dict_to_single_dict
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _flatten_zero_shot_text_classifier_output_to_df(self, data): """ Converts the output of sequences, labels, and scores to a Pandas DataFrame output. Example input: [{'sequence': 'My dog loves to eat spaghetti', 'labels': ['happy', 'sad'], 'scores': [0.98969709873...
Converts the output of sequences, labels, and scores to a Pandas DataFrame output. Example input: [{'sequence': 'My dog loves to eat spaghetti', 'labels': ['happy', 'sad'], 'scores': [0.9896970987319946, 0.010302911512553692]}, {'sequence': 'My dog hates going to ...
_flatten_zero_shot_text_classifier_output_to_df
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _strip_input_from_response_in_instruction_pipelines( self, input_data, output, output_key, flavor_config, include_prompt=True, collapse_whitespace=False, ): """ Parse the output from instruction pipelines to conform with other text generato...
Parse the output from instruction pipelines to conform with other text generator pipeline types and remove line feed characters and other confusing outputs
_strip_input_from_response_in_instruction_pipelines
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _wrap_strings_as_list_if_scalar(output_data): """ Wraps single string outputs in a list to support batch processing logic in serving. Scalar values are not supported for processing in batch logic as they cannot be coerced to DataFrame representations. """ if isinstanc...
Wraps single string outputs in a list to support batch processing logic in serving. Scalar values are not supported for processing in batch logic as they cannot be coerced to DataFrame representations.
_wrap_strings_as_list_if_scalar
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_lists_of_dict_to_list_of_str(self, output_data, target_dict_key) -> list[str]: """ Parses the output results from select Pipeline types to extract specific values from a target key. Examples (with "a" as the `target_dict_key`): Input: [{"a": "valid", "b": "invalid"}, ...
Parses the output results from select Pipeline types to extract specific values from a target key. Examples (with "a" as the `target_dict_key`): Input: [{"a": "valid", "b": "invalid"}, {"a": "another valid", "c": invalid"}] Output: ["valid", "another_valid"] Input: [{"...
_parse_lists_of_dict_to_list_of_str
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_feature_extraction_output(output_data): """ Parse the return type from a FeatureExtractionPipeline output. The mixed types for input are present depending on how the pyfunc is instantiated. For model serving usage, the returned type from MLServer will be a numpy.ndarray type, ...
Parse the return type from a FeatureExtractionPipeline output. The mixed types for input are present depending on how the pyfunc is instantiated. For model serving usage, the returned type from MLServer will be a numpy.ndarray type, otherwise, the return within a manually executed pyfun...
_parse_feature_extraction_output
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_tokenizer_output(self, output_data, target_set): """ Parses the tokenizer pipeline output. Examples: Input: [{"entity": "PRON", "score": 0.95}, {"entity": "NOUN", "score": 0.998}] Output: "PRON,NOUN" Input: [[{"entity": "PRON", "score": 0.95}, {"entity": "NO...
Parses the tokenizer pipeline output. Examples: Input: [{"entity": "PRON", "score": 0.95}, {"entity": "NOUN", "score": 0.998}] Output: "PRON,NOUN" Input: [[{"entity": "PRON", "score": 0.95}, {"entity": "NOUN", "score": 0.998}], [{"entity": "PRON", "score": 0.9...
_parse_tokenizer_output
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_list_of_multiple_dicts(output_data, target_dict_key): """ Returns the first value of the `target_dict_key` that matches in the first dictionary in a list of dictionaries. """ def fetch_target_key_value(data, key): if isinstance(data[0], dict): ...
Returns the first value of the `target_dict_key` that matches in the first dictionary in a list of dictionaries.
_parse_list_of_multiple_dicts
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_question_answer_input(self, data): """ Parses the single string input representation for a question answer pipeline into the required dict format for a `question-answering` pipeline. """ if isinstance(data, list): return [self._parse_question_answer_input(e...
Parses the single string input representation for a question answer pipeline into the required dict format for a `question-answering` pipeline.
_parse_question_answer_input
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_json_encoded_list(self, data, key_to_unpack): """ Parses the complex input types for pipelines such as ZeroShotClassification in which the required input type is Dict[str, Union[str, List[str]]] wherein the list provided is encoded as JSON. This method unpacks that string to t...
Parses the complex input types for pipelines such as ZeroShotClassification in which the required input type is Dict[str, Union[str, List[str]]] wherein the list provided is encoded as JSON. This method unpacks that string to the required elements.
_parse_json_encoded_list
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _parse_json_encoded_dict_payload_to_dict(data, key_to_unpack): """ Parses complex dict input types that have been json encoded. Pipelines like TableQuestionAnswering require such input types. """ if isinstance(data, list): return [ { ...
Parses complex dict input types that have been json encoded. Pipelines like TableQuestionAnswering require such input types.
_parse_json_encoded_dict_payload_to_dict
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _convert_cast_lists_from_np_back_to_list(data): """ This handles the casting of dicts within lists from Pandas DF conversion within model serving back into the required Dict[str, List[str]] if this type matching occurs. Otherwise, it's a noop. """ if not isinstance(da...
This handles the casting of dicts within lists from Pandas DF conversion within model serving back into the required Dict[str, List[str]] if this type matching occurs. Otherwise, it's a noop.
_convert_cast_lists_from_np_back_to_list
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def is_base64_image(image): """Check whether input image is a base64 encoded""" try: b64_decoded_image = base64.b64decode(image) return ( base64.b64encode(b64_decoded_image).decode("utf-8") == image or base64.encodebytes(b64_decoded_image).decode(...
Check whether input image is a base64 encoded
is_base64_image
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _convert_image_input(self, input_data): """ Conversion utility for decoding the base64 encoded bytes data of a raw image file when parsed through model serving, if applicable. Direct usage of the pyfunc implementation outside of model serving will treat this utility as a noop. ...
Conversion utility for decoding the base64 encoded bytes data of a raw image file when parsed through model serving, if applicable. Direct usage of the pyfunc implementation outside of model serving will treat this utility as a noop. For reference, the expected encoding for input to Mo...
_convert_image_input
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _convert_audio_input( self, data: Union[AudioInput, list[dict[int, list[AudioInput]]]] ) -> Union[AudioInput, list[AudioInput]]: """ Convert the input data into the format that the Transformers pipeline expects. Args: data: The input data to be converted. This can be...
Convert the input data into the format that the Transformers pipeline expects. Args: data: The input data to be converted. This can be one of the following: 1. A single input audio data (bytes, numpy array, or a path or URI to an audio file) 2. List of dicti...
_convert_audio_input
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _decode_audio(self, audio: AudioInput) -> AudioInput: """ Decode the audio data if it is base64 encoded bytes, otherwise no-op. """ if isinstance(audio, str): # Input is an URI to the audio file to be processed. self._validate_str_input_uri_or_file(audio) ...
Decode the audio data if it is base64 encoded bytes, otherwise no-op.
_decode_audio
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def is_base64_audio(audio: bytes) -> bool: """Check whether input audio is a base64 encoded""" try: return base64.b64encode(base64.b64decode(audio)) == audio except binascii.Error: return False
Check whether input audio is a base64 encoded
is_base64_audio
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _validate_str_input_uri_or_file(input_str): """ Validation of blob references to either audio or image files, if a string is input to the ``predict`` method, perform validation of the string contents by checking for a valid uri or filesystem reference instead of surfacing the...
Validation of blob references to either audio or image files, if a string is input to the ``predict`` method, perform validation of the string contents by checking for a valid uri or filesystem reference instead of surfacing the cryptic stack trace that is otherwise raised for a...
_validate_str_input_uri_or_file
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def _format_prompt_template(self, input_data): """ Wraps the input data in the specified prompt template. If no template is specified, or if the pipeline is an unsupported type, or if the input type is not a string or list of strings, then the input data is returned unchanged. ""...
Wraps the input data in the specified prompt template. If no template is specified, or if the pipeline is an unsupported type, or if the input type is not a string or list of strings, then the input data is returned unchanged.
_format_prompt_template
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def autolog( log_input_examples=False, log_model_signatures=False, log_models=False, log_datasets=False, disable=False, exclusive=False, disable_for_unsupported_versions=False, silent=False, extra_tags=None, ): """ This autologging integration is solely used for disabling spu...
This autologging integration is solely used for disabling spurious autologging of irrelevant sub-models that are created during the training and evaluation of transformers-based models. Autologging functionality is not implemented fully for the transformers flavor.
autolog
python
mlflow/mlflow
mlflow/transformers/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/transformers/__init__.py
Apache-2.0
def check_content_and_tool_calls(cls, values): """ Ensure at least one of 'content' or 'tool_calls' is set. """ if IS_PYDANTIC_V2_OR_NEWER: content = values.content tool_calls = values.tool_calls else: content = values.get("content") ...
Ensure at least one of 'content' or 'tool_calls' is set.
check_content_and_tool_calls
python
mlflow/mlflow
mlflow/types/agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/agent.py
Apache-2.0
def check_tool_messages(cls, values): """ Ensure that the 'name' and 'tool_call_id' fields are set for tool messages. """ if IS_PYDANTIC_V2_OR_NEWER: name = values.name role = values.role tool_call_id = values.tool_call_id else: nam...
Ensure that the 'name' and 'tool_call_id' fields are set for tool messages.
check_tool_messages
python
mlflow/mlflow
mlflow/types/agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/agent.py
Apache-2.0
def check_message_ids(cls, values): """ Ensure that all messages have an ID and it is unique. """ if IS_PYDANTIC_V2_OR_NEWER: message_ids = [msg.id for msg in values.messages] else: message_ids = [msg.get("id") for msg in values.get("messages")] i...
Ensure that all messages have an ID and it is unique.
check_message_ids
python
mlflow/mlflow
mlflow/types/agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/agent.py
Apache-2.0
def check_message_id(cls, values): """ Ensure that the message ID is unique. """ message_id = values.delta.id if IS_PYDANTIC_V2_OR_NEWER else values.get("delta").get("id") if message_id is None: raise ValueError( "The field `delta` of ChatAgentChunk m...
Ensure that the message ID is unique.
check_message_id
python
mlflow/mlflow
mlflow/types/agent.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/agent.py
Apache-2.0
def from_dict(cls, data): """ Create an instance of the class from a dict, ignoring any undefined fields. This is useful when the dict contains extra fields, causing cls(**data) to fail. """ field_names = [field.name for field in fields(cls)] filtered_data = {k: v for k, ...
Create an instance of the class from a dict, ignoring any undefined fields. This is useful when the dict contains extra fields, causing cls(**data) to fail.
from_dict
python
mlflow/mlflow
mlflow/types/llm.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/llm.py
Apache-2.0
def output_text(self) -> str: """Convenience property that aggregates all `output_text` items from the `output` list. If no `output_text` content blocks exist, then an empty string is returned. """ texts: list[str] = [] for output in self.output: if output.ty...
Convenience property that aggregates all `output_text` items from the `output` list. If no `output_text` content blocks exist, then an empty string is returned.
output_text
python
mlflow/mlflow
mlflow/types/responses_helpers.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/responses_helpers.py
Apache-2.0
def __eq__(self, other) -> bool: """ Determine if two objects are equal. """
Determine if two objects are equal.
__eq__
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def __repr__(self) -> str: """ The string representation of the object. """
The string representation of the object.
__repr__
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def _merge(self, other: BaseType) -> BaseType: """ Merge two objects and return the updated object if they're compatible. """
Merge two objects and return the updated object if they're compatible.
_merge
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def __init__( self, name: str, dtype: ALLOWED_DTYPES, required: bool = True, ) -> None: """ Args: name: The name of the property dtype: The data type of the property required: Whether this property is required """ if...
Args: name: The name of the property dtype: The data type of the property required: Whether this property is required
__init__
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain only one key as `name`, and the value should be a dictionary containing `type` and optional `required` keys. Example: {"property_name": {"type": "string...
Deserialize from a json loaded dictionary. The dictionary is expected to contain only one key as `name`, and the value should be a dictionary containing `type` and optional `required` keys. Example: {"property_name": {"type": "string", "required": True}}
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def _merge(self, other: BaseType) -> Property: """ Check if current property is compatible with another property and return the updated property. When two properties have the same name, we need to check if their dtypes are compatible or not. An example of two compatible p...
Check if current property is compatible with another property and return the updated property. When two properties have the same name, we need to check if their dtypes are compatible or not. An example of two compatible properties: .. code-block:: python ...
_merge
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `properties` keys. Example: {"type": "object", "properties": {"property_name": {"type": "string"}}} """ if not {"properties", "type"}...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `properties` keys. Example: {"type": "object", "properties": {"property_name": {"type": "string"}}}
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def _merge(self, other: BaseType) -> Object: """ Check if the current object is compatible with another object and return the updated object. When we infer the signature from a list of objects, it is possible that one object has more properties than the other. In this case, ...
Check if the current object is compatible with another object and return the updated object. When we infer the signature from a list of objects, it is possible that one object has more properties than the other. In this case, we should mark those optional properties as required=...
_merge
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `items` keys. Example: {"type": "array", "items": "string"} """ if not {"items", "type"} <= set(kwargs.keys()): raise Mlf...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `items` keys. Example: {"type": "array", "items": "string"}
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `values` keys. Example: {"type": "map", "values": "string"} """ if not {"values", "type"} <= set(kwargs.keys()): raise Ml...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `values` keys. Example: {"type": "map", "values": "string"}
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def __init__(self): """ AnyType can store any json-serializable data including None values. For example: .. code-block::python from mlflow.types.schema import AnyType, Schema, ColSpec schema = Schema([ColSpec(type=AnyType(), name="id")]) .. Note:: ...
AnyType can store any json-serializable data including None values. For example: .. code-block::python from mlflow.types.schema import AnyType, Schema, ColSpec schema = Schema([ColSpec(type=AnyType(), name="id")]) .. Note:: AnyType should be used ...
__init__
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and optional `name` and `required` keys. """ if not {"type"} <= set(kwargs.keys()): raise MlflowException("Missing keys in ColSpec JS...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and optional `name` and `required` keys.
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `dtype` and `shape` keys. """ if not {"dtype", "shape"} <= set(kwargs.keys()): raise MlflowException( "Missing keys in TensorSpec JS...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `dtype` and `shape` keys.
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `tensor-spec` keys. """ if not {"tensor-spec", "type"} <= set(kwargs.keys()): raise MlflowException( "Missing keys in Ten...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `tensor-spec` keys.
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def input_types_dict(self) -> dict[str, Union[DataType, np.dtype, Array, Object]]: """Maps column names to types, iff this schema declares names.""" if not self.has_input_names(): raise MlflowException("Cannot get input types as a dict for schema without names.") return {x.name: x.ty...
Maps column names to types, iff this schema declares names.
input_types_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def input_dict(self) -> dict[str, Union[ColSpec, TensorSpec]]: """Maps column names to inputs, iff this schema declares names.""" if not self.has_input_names(): raise MlflowException("Cannot get input dict for schema without names.") return {x.name: x for x in self.inputs}
Maps column names to inputs, iff this schema declares names.
input_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def numpy_types(self) -> list[np.dtype]: """Convenience shortcut to get the datatypes as numpy types.""" if self.is_tensor_spec(): return [x.type for x in self.inputs] if all(isinstance(x.type, DataType) for x in self.inputs): return [x.type.to_numpy() for x in self.input...
Convenience shortcut to get the datatypes as numpy types.
numpy_types
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def pandas_types(self) -> list[np.dtype]: """Convenience shortcut to get the datatypes as pandas types. Unsupported by TensorSpec.""" if self.is_tensor_spec(): raise MlflowException("TensorSpec only supports numpy types, use numpy_types() instead") if all(isinstance(x.type, DataType)...
Convenience shortcut to get the datatypes as pandas types. Unsupported by TensorSpec.
pandas_types
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def as_spark_schema(self): """Convert to Spark schema. If this schema is a single unnamed column, it is converted directly the corresponding spark data type, otherwise it's returned as a struct (missing column names are filled with an integer sequence). Unsupported by TensorSpec. ...
Convert to Spark schema. If this schema is a single unnamed column, it is converted directly the corresponding spark data type, otherwise it's returned as a struct (missing column names are filled with an integer sequence). Unsupported by TensorSpec.
as_spark_schema
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def validate_type_and_shape( cls, spec: str, value: Any, value_type: Union[DataType, Object], shape: Optional[tuple[int, ...]], ): """ Validate that the value has the expected type and shape. """ from mlflow.models.utils import _enforce_object,...
Validate that the value has the expected type and shape.
validate_type_and_shape
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def from_json_dict(cls, **kwargs): """ Deserialize from a json loaded dictionary. The dictionary is expected to contain `name`, `type` and `default` keys. """ # For backward compatibility, we accept both `type` and `dtype` keys required_keys1 = {"name", "dtype", "default"...
Deserialize from a json loaded dictionary. The dictionary is expected to contain `name`, `type` and `default` keys.
from_json_dict
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def _get_dataclass_annotations(cls) -> dict[str, Any]: """ Given a dataclass or an instance of one, collect annotations from it and all its parent dataclasses. """ if not is_dataclass(cls): raise TypeError(f"{cls.__name__} is not a dataclass.") annotations = {} effective_class = cls...
Given a dataclass or an instance of one, collect annotations from it and all its parent dataclasses.
_get_dataclass_annotations
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def convert_dataclass_to_schema(dataclass): """ Converts a given dataclass into a Schema object. The dataclass must include type hints for all its fields. Fields can be of basic types, other dataclasses, or Lists/Optional of these types. Union types are not supported. Only the top-level fields are direc...
Converts a given dataclass into a Schema object. The dataclass must include type hints for all its fields. Fields can be of basic types, other dataclasses, or Lists/Optional of these types. Union types are not supported. Only the top-level fields are directly converted to ColSpecs, while nested fields ...
convert_dataclass_to_schema
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def _convert_dataclass_to_nested_object(dataclass): """ Convert a nested dataclass to an Object type used within a ColSpec. """ properties = [] for field_name, field_type in dataclass.__annotations__.items(): properties.append(_convert_field_to_property(field_name, field_type)) return Ob...
Convert a nested dataclass to an Object type used within a ColSpec.
_convert_dataclass_to_nested_object
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def _convert_field_to_property(field_name, field_type): """ Helper function to convert a single field to a Property object suitable for inclusion in an Object. """ is_optional = False effective_type = field_type if get_origin(field_type) == Union and type(None) in get_args(field_type): ...
Helper function to convert a single field to a Property object suitable for inclusion in an Object.
_convert_field_to_property
python
mlflow/mlflow
mlflow/types/schema.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/schema.py
Apache-2.0
def type_hints_no_signature_inference(): """ This function returns a tuple of types that can be used as type hints, but no schema can be inferred from them. ..note:: These types can not be used as nested types in other type hints. """ type_hints = () try: import pandas as pd...
This function returns a tuple of types that can be used as type hints, but no schema can be inferred from them. ..note:: These types can not be used as nested types in other type hints.
type_hints_no_signature_inference
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _infer_colspec_type_from_type_hint(type_hint: type[Any]) -> ColSpecType: """ Infer the ColSpec type from a type hint. The inferred dtype should be one of the supported data types in COLSPEC_TYPES. """ if type_hint == Any: color_warning( message="Any type hint is inferred as A...
Infer the ColSpec type from a type hint. The inferred dtype should be one of the supported data types in COLSPEC_TYPES.
_infer_colspec_type_from_type_hint
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _infer_type_from_pydantic_model(model: pydantic.BaseModel) -> Object: """ Infer the object schema from a pydantic model. """ if _is_pydantic_type_hint(model): fields = model_fields(model) else: raise TypeError(f"model must be a Pydantic model class, but got {type(model)}") p...
Infer the object schema from a pydantic model.
_infer_type_from_pydantic_model
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _get_element_type_of_list_type_hint(type_hint: type[list[Any]]) -> Any: """ Get the element type of list[...] type hint """ args = get_args(type_hint) # Optional[list[...]] if type(None) in args: raise MlflowException.invalid_parameter_value(OPTIONAL_INPUT_MSG) # a valid list[......
Get the element type of list[...] type hint
_get_element_type_of_list_type_hint
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _infer_schema_from_list_type_hint(type_hint: type[list[Any]]) -> Schema: """ Infer schema from a list type hint. The type hint must be list[...], and the inferred schema contains a single ColSpec, where the type is based on the element type of the list type hint, since ColSpec represents a colum...
Infer schema from a list type hint. The type hint must be list[...], and the inferred schema contains a single ColSpec, where the type is based on the element type of the list type hint, since ColSpec represents a column's data type of the dataset. e.g. list[int] -> Schema([ColSpec(type=DataType.lo...
_infer_schema_from_list_type_hint
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _validate_data_against_type_hint(data: Any, type_hint: type[Any]) -> Any: """ Validate the data against provided type hint. The allowed conversions are: dictionary data with Pydantic model type hint -> Pydantic model instance Args: data: The data to validate type_hint: The t...
Validate the data against provided type hint. The allowed conversions are: dictionary data with Pydantic model type hint -> Pydantic model instance Args: data: The data to validate type_hint: The type hint to validate against
_validate_data_against_type_hint
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _parse_data_for_datatype_hint(data: Any, type_hint: type[Any]) -> Any: """ Parse the data based on the type hint. This should only be used in MLflow serving environment to convert json data to the expected format. Allowed conversions: - string data with datetime type hint -> datetime obj...
Parse the data based on the type hint. This should only be used in MLflow serving environment to convert json data to the expected format. Allowed conversions: - string data with datetime type hint -> datetime object - string data with bytes type hint -> bytes object
_parse_data_for_datatype_hint
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _get_origin_type(type_hint: type[Any]) -> Any: """ Get the origin type of a type hint. If the type hint is Union type, return the origin type of the effective type. If the type hint is Union type with multiple effective types, return Any. """ origin_type = get_origin(type_hint) if origin...
Get the origin type of a type hint. If the type hint is Union type, return the origin type of the effective type. If the type hint is Union type with multiple effective types, return Any.
_get_origin_type
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _convert_data_to_type_hint(data: Any, type_hint: type[Any]) -> Any: """ Convert data to the expected format based on the type hint. This function is used in data validation of @pyfunc to support compatibility with functions such as mlflow.evaluate and spark_udf since they accept pandas DF as input. ...
Convert data to the expected format based on the type hint. This function is used in data validation of @pyfunc to support compatibility with functions such as mlflow.evaluate and spark_udf since they accept pandas DF as input. NB: the input pandas DataFrame must contain a single column with the same t...
_convert_data_to_type_hint
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _sanitize_data(data: Any) -> Any: """ Sanitize the data by converting any numpy lists to Python lists. This is needed because spark_udf (pandas_udf) implicitly converts lists into numpy arrays. For example, below udf demonstrates the behavior: df = spark.createDataFrame(pd.DataFrame({"input...
Sanitize the data by converting any numpy lists to Python lists. This is needed because spark_udf (pandas_udf) implicitly converts lists into numpy arrays. For example, below udf demonstrates the behavior: df = spark.createDataFrame(pd.DataFrame({"input": [["a", "b"], ["c", "d"]]})) @panda...
_sanitize_data
python
mlflow/mlflow
mlflow/types/type_hints.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/type_hints.py
Apache-2.0
def _get_tensor_shape(data, variable_dimension: Optional[int] = 0) -> tuple: """Infer the shape of the inputted data. This method creates the shape of the tensor to store in the TensorSpec. The variable dimension is assumed to be the first dimension by default. This assumption can be overridden by inputtin...
Infer the shape of the inputted data. This method creates the shape of the tensor to store in the TensorSpec. The variable dimension is assumed to be the first dimension by default. This assumption can be overridden by inputting a different variable dimension or `None` to represent that the input tensor do...
_get_tensor_shape
python
mlflow/mlflow
mlflow/types/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/utils.py
Apache-2.0
def clean_tensor_type(dtype: np.dtype): """ This method strips away the size information stored in flexible datatypes such as np.str_ and np.bytes_. Other numpy dtypes are returned unchanged. Args: dtype: Numpy dtype of a tensor Returns: dtype: Cleaned numpy dtype """ if no...
This method strips away the size information stored in flexible datatypes such as np.str_ and np.bytes_. Other numpy dtypes are returned unchanged. Args: dtype: Numpy dtype of a tensor Returns: dtype: Cleaned numpy dtype
clean_tensor_type
python
mlflow/mlflow
mlflow/types/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/utils.py
Apache-2.0
def _infer_colspec_type(data: Any) -> Union[DataType, Array, Object, AnyType]: """ Infer an MLflow Colspec type from the dataset. Args: data: data to infer from. Returns: Object """ dtype = _infer_datatype(data) if dtype is None: raise MlflowException( ...
Infer an MLflow Colspec type from the dataset. Args: data: data to infer from. Returns: Object
_infer_colspec_type
python
mlflow/mlflow
mlflow/types/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/utils.py
Apache-2.0
def _infer_datatype(data: Any) -> Optional[Union[DataType, Array, Object, AnyType]]: """ Infer the datatype of input data. Data type and inferred schema type mapping: - dict -> Object - list -> Array - numpy.ndarray -> Array - scalar -> DataType - None, empty dictiona...
Infer the datatype of input data. Data type and inferred schema type mapping: - dict -> Object - list -> Array - numpy.ndarray -> Array - scalar -> DataType - None, empty dictionary/list -> AnyType .. Note:: Empty numpy arrays are inferred as None to keep th...
_infer_datatype
python
mlflow/mlflow
mlflow/types/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/utils.py
Apache-2.0
def _infer_array_datatype(data: Union[list, np.ndarray]) -> Optional[Array]: """Infer schema from an array. This tries to infer type if there is at least one non-null item in the list, assuming the list has a homogeneous type. However, if the list is empty or all items are null, returns None as a sign of un...
Infer schema from an array. This tries to infer type if there is at least one non-null item in the list, assuming the list has a homogeneous type. However, if the list is empty or all items are null, returns None as a sign of undetermined. E.g. ["a", "b"] => Array(string) ["a", None] => Arr...
_infer_array_datatype
python
mlflow/mlflow
mlflow/types/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/utils.py
Apache-2.0
def _infer_schema(data: Any) -> Schema: """ Infer an MLflow schema from a dataset. Data inputted as a numpy array or a dictionary is represented by :py:class:`TensorSpec`. All other inputted data types are specified by :py:class:`ColSpec`. A `TensorSpec` captures the data shape (default variable a...
Infer an MLflow schema from a dataset. Data inputted as a numpy array or a dictionary is represented by :py:class:`TensorSpec`. All other inputted data types are specified by :py:class:`ColSpec`. A `TensorSpec` captures the data shape (default variable axis is 0), the data type (numpy.dtype) and ...
_infer_schema
python
mlflow/mlflow
mlflow/types/utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/types/utils.py
Apache-2.0
def _get_min_indent_of_docstring(docstring_str: str) -> str: """ Get the minimum indentation string of a docstring, based on the assumption that the closing triple quote for multiline comments must be on a new line. Note that based on ruff rule D209, the closing triple quote for multiline comments m...
Get the minimum indentation string of a docstring, based on the assumption that the closing triple quote for multiline comments must be on a new line. Note that based on ruff rule D209, the closing triple quote for multiline comments must be on a new line. Args: docstring_str: string with ...
_get_min_indent_of_docstring
python
mlflow/mlflow
mlflow/utils/annotations.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/annotations.py
Apache-2.0
def experimental(api_or_type: Union[C, str]) -> C: """Decorator / decorator creator for marking APIs experimental in the docstring. Args: api_or_type: An API to mark, or an API typestring for which to generate a decorator. Returns: Decorated API (if a ``api_or_type`` is an API) or a functi...
Decorator / decorator creator for marking APIs experimental in the docstring. Args: api_or_type: An API to mark, or an API typestring for which to generate a decorator. Returns: Decorated API (if a ``api_or_type`` is an API) or a function that decorates the specified API type (if ``api...
experimental
python
mlflow/mlflow
mlflow/utils/annotations.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/annotations.py
Apache-2.0
def deprecated( alternative: Optional[str] = None, since: Optional[str] = None, impact: Optional[str] = None ): """Annotation decorator for marking APIs as deprecated in docstrings and raising a warning if called. Args: alternative: The name of a superseded replacement function, method, ...
Annotation decorator for marking APIs as deprecated in docstrings and raising a warning if called. Args: alternative: The name of a superseded replacement function, method, or class to use in place of the deprecated one. since: A version designator defining during which release the ...
deprecated
python
mlflow/mlflow
mlflow/utils/annotations.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/annotations.py
Apache-2.0
def keyword_only(func): """A decorator that forces keyword arguments in the wrapped method.""" @wraps(func) def wrapper(*args, **kwargs): if len(args) > 0: raise TypeError(f"Method {func.__name__} only takes keyword arguments.") return func(**kwargs) indent = _get_min_inden...
A decorator that forces keyword arguments in the wrapped method.
keyword_only
python
mlflow/mlflow
mlflow/utils/annotations.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/annotations.py
Apache-2.0
def filter_user_warnings_once(func): """A decorator that filter user warnings to only show once in the wrapped method.""" @wraps(func) def wrapper(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("once", category=UserWarning) return func(*args, **kwarg...
A decorator that filter user warnings to only show once in the wrapped method.
filter_user_warnings_once
python
mlflow/mlflow
mlflow/utils/annotations.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/annotations.py
Apache-2.0
def _get_arg_names(f): """Get the argument names of a function. Args: f: A function. Returns: A list of argument names. """ # `inspect.getargspec` or `inspect.getfullargspec` doesn't work properly for a wrapped function. # See https://hynek.me/articles/decorators#mangled-signa...
Get the argument names of a function. Args: f: A function. Returns: A list of argument names.
_get_arg_names
python
mlflow/mlflow
mlflow/utils/arguments_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/arguments_utils.py
Apache-2.0
def get_conda_bin_executable(executable_name): """ Return path to the specified executable, assumed to be discoverable within the 'bin' subdirectory of a conda installation. The conda home directory (expected to contain a 'bin' subdirectory) is configurable via the ``mlflow.projects.MLFLOW_CONDA_HO...
Return path to the specified executable, assumed to be discoverable within the 'bin' subdirectory of a conda installation. The conda home directory (expected to contain a 'bin' subdirectory) is configurable via the ``mlflow.projects.MLFLOW_CONDA_HOME`` environment variable. If ``mlflow.projects.ML...
get_conda_bin_executable
python
mlflow/mlflow
mlflow/utils/conda.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py
Apache-2.0
def _list_conda_environments(extra_env=None): """Return a list of names of conda environments. Args: extra_env: Extra environment variables for running "conda env list" command. """ prc = process._exec_cmd( [get_conda_bin_executable("conda"), "env", "list", "--json"], extra_env=extra_e...
Return a list of names of conda environments. Args: extra_env: Extra environment variables for running "conda env list" command.
_list_conda_environments
python
mlflow/mlflow
mlflow/utils/conda.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py
Apache-2.0
def _create_conda_env_retry( conda_env_path, conda_env_create_path, project_env_name, conda_extra_env_vars, _capture_output ): """ `conda env create` command can fail due to network issues such as `ConnectionResetError` while collecting package metadata. This function retries the command up to 3 times. ...
`conda env create` command can fail due to network issues such as `ConnectionResetError` while collecting package metadata. This function retries the command up to 3 times.
_create_conda_env_retry
python
mlflow/mlflow
mlflow/utils/conda.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py
Apache-2.0
def _get_conda_extra_env_vars(env_root_dir=None): """ Given the `env_root_dir` (See doc of PyFuncBackend constructor argument `env_root_dir`), return a dict of environment variables which are used to config conda to generate envs under the expected `env_root_dir`. """ if env_root_dir is None: ...
Given the `env_root_dir` (See doc of PyFuncBackend constructor argument `env_root_dir`), return a dict of environment variables which are used to config conda to generate envs under the expected `env_root_dir`.
_get_conda_extra_env_vars
python
mlflow/mlflow
mlflow/utils/conda.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py
Apache-2.0
def get_or_create_conda_env( conda_env_path, env_id=None, capture_output=False, env_root_dir=None, pip_requirements_override=None, extra_envs=None, ): """Given a `Project`, creates a conda environment containing the project's dependencies if such a conda environment doesn't already exist...
Given a `Project`, creates a conda environment containing the project's dependencies if such a conda environment doesn't already exist. Returns the name of the conda environment. Args: conda_env_path: Path to a conda yaml file. env_id: Optional string that is added to the contents of the yaml f...
get_or_create_conda_env
python
mlflow/mlflow
mlflow/utils/conda.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py
Apache-2.0
def _get_conda_dependencies(conda_yaml_path): """Extracts conda dependencies from a conda yaml file. Args: conda_yaml_path: Conda yaml file path. """ with open(conda_yaml_path) as f: conda_yaml = yaml.safe_load(f) return [d for d in conda_yaml.get("dependencies", []) if isinstan...
Extracts conda dependencies from a conda yaml file. Args: conda_yaml_path: Conda yaml file path.
_get_conda_dependencies
python
mlflow/mlflow
mlflow/utils/conda.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/conda.py
Apache-2.0
def login(backend: str = "databricks", interactive: bool = True) -> None: """Configure MLflow server authentication and connect MLflow to tracking server. This method provides a simple way to connect MLflow to its tracking server. Currently only Databricks tracking server is supported. Users will be prompt...
Configure MLflow server authentication and connect MLflow to tracking server. This method provides a simple way to connect MLflow to its tracking server. Currently only Databricks tracking server is supported. Users will be prompted to enter the credentials if no existing Databricks profile is found, and t...
login
python
mlflow/mlflow
mlflow/utils/credentials.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/credentials.py
Apache-2.0
def _overwrite_or_create_databricks_profile( file_name, profile, profile_name="DEFAULT", ): """Overwrite or create a profile in the databricks config file. Args: file_name: string, the file name of the databricks config file, usually `~/.databrickscfg`. profile: dict, contains the a...
Overwrite or create a profile in the databricks config file. Args: file_name: string, the file name of the databricks config file, usually `~/.databrickscfg`. profile: dict, contains the authentiacation profile information. profile_name: string, the name of the profile to be overwritten or ...
_overwrite_or_create_databricks_profile
python
mlflow/mlflow
mlflow/utils/credentials.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/credentials.py
Apache-2.0