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 _generate_random_name(sep="-", integer_scale=3, max_length=20): """Helper function for generating a random predicate, noun, and integer combination Args: sep: String separator for word spacing. integer_scale: Dictates the maximum scale range for random integer sampling (power of 10). ...
Helper function for generating a random predicate, noun, and integer combination Args: sep: String separator for word spacing. integer_scale: Dictates the maximum scale range for random integer sampling (power of 10). max_length: Maximum allowable string length. Returns: A rand...
_generate_random_name
python
mlflow/mlflow
mlflow/utils/name_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/name_utils.py
Apache-2.0
def refresh(self, logger=None): """Validates the token or API key configured for accessing the OpenAI resource.""" if self._api_token_env is not None: return if self._is_azure_ad: if not self._azure_ad_token or self._azure_ad_token.expires_on < time.time() + 60: ...
Validates the token or API key configured for accessing the OpenAI resource.
refresh
python
mlflow/mlflow
mlflow/utils/openai_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/openai_utils.py
Apache-2.0
def get_oss_host_creds(server_uri=None): """ Retrieve the host credentials for the OSS server. Args: server_uri (str): The URI of the server. Returns: MlflowHostCreds: The host credentials for the OSS server. """ parsed_uri = urllib.parse.urlparse(server_uri) if parsed_uri...
Retrieve the host credentials for the OSS server. Args: server_uri (str): The URI of the server. Returns: MlflowHostCreds: The host credentials for the OSS server.
get_oss_host_creds
python
mlflow/mlflow
mlflow/utils/oss_registry_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/oss_registry_utils.py
Apache-2.0
def _remove_inaccessible_python_path(env): """ Remove inaccessible path from PYTHONPATH environment variable. """ if python_path := env.get("PYTHONPATH"): paths = [p for p in python_path.split(":") if os.access(p, os.R_OK)] env["PYTHONPATH"] = ":".join(paths) return env
Remove inaccessible path from PYTHONPATH environment variable.
_remove_inaccessible_python_path
python
mlflow/mlflow
mlflow/utils/process.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/process.py
Apache-2.0
def _exec_cmd( cmd, *, throw_on_error=True, extra_env=None, capture_output=True, synchronous=True, stream_output=False, **kwargs, ): """A convenience wrapper of `subprocess.Popen` for running a command from a Python script. Args: cmd: The command to run, as a string or a...
A convenience wrapper of `subprocess.Popen` for running a command from a Python script. Args: cmd: The command to run, as a string or a list of strings. throw_on_error: If True, raises an Exception if the exit code of the program is nonzero. extra_env: Extra environment variables to be defi...
_exec_cmd
python
mlflow/mlflow
mlflow/utils/process.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/process.py
Apache-2.0
def cache_return_value_per_process(fn): """ A decorator which globally caches the return value of the decorated function. But if current process forked out a new child process, in child process, old cache values are invalidated. Restrictions: The decorated function must be called with only position...
A decorator which globally caches the return value of the decorated function. But if current process forked out a new child process, in child process, old cache values are invalidated. Restrictions: The decorated function must be called with only positional arguments, and all the argument values m...
cache_return_value_per_process
python
mlflow/mlflow
mlflow/utils/process.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/process.py
Apache-2.0
def _mark_int64_fields_for_proto_maps(proto_map, value_field_type): """Converts a proto map to JSON, preserving only int64-related fields.""" json_dict = {} for key, value in proto_map.items(): # The value of a protobuf map can only be a scalar or a message (not a map or repeated # field). ...
Converts a proto map to JSON, preserving only int64-related fields.
_mark_int64_fields_for_proto_maps
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def _mark_int64_fields(proto_message): """Converts a proto message to JSON, preserving only int64-related fields.""" json_dict = {} for field, value in proto_message.ListFields(): if ( # These three conditions check if this field is a protobuf map. # See the official implemen...
Converts a proto message to JSON, preserving only int64-related fields.
_mark_int64_fields
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def _merge_json_dicts(from_dict, to_dict): """Merges the json elements of from_dict into to_dict. Only works for json dicts converted from proto messages """ for key, value in from_dict.items(): if isinstance(key, int) and str(key) in to_dict: # When the key (i.e. the proto field nam...
Merges the json elements of from_dict into to_dict. Only works for json dicts converted from proto messages
_merge_json_dicts
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def message_to_json(message): """Converts a message to JSON, using snake_case for field names.""" # Google's MessageToJson API converts int64 proto fields to JSON strings. # For more info, see https://github.com/protocolbuffers/protobuf/issues/2954 json_dict_with_int64_as_str = json.loads( Mess...
Converts a message to JSON, using snake_case for field names.
message_to_json
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def _stringify_all_experiment_ids(x): """Converts experiment_id fields which are defined as ints into strings in the given json. This is necessary for backwards- and forwards-compatibility with MLflow clients/servers running MLflow 0.9.0 and below, as experiment_id was changed from an int to a string. T...
Converts experiment_id fields which are defined as ints into strings in the given json. This is necessary for backwards- and forwards-compatibility with MLflow clients/servers running MLflow 0.9.0 and below, as experiment_id was changed from an int to a string. To note, the Python JSON serializer is happy t...
_stringify_all_experiment_ids
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def parse_dict(js_dict, message): """Parses a JSON dictionary into a message proto, ignoring unknown fields in the JSON.""" _stringify_all_experiment_ids(js_dict) ParseDict(js_dict=js_dict, message=message, ignore_unknown_fields=True)
Parses a JSON dictionary into a message proto, ignoring unknown fields in the JSON.
parse_dict
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def set_pb_value(proto: Value, value: Any): """ DO NOT USE THIS FUNCTION. Preserved for backwards compatibility. Set a value to the google.protobuf.Value object. """ if isinstance(value, dict): for key, val in value.items(): set_pb_value(proto.struct_value.fields[key], val) ...
DO NOT USE THIS FUNCTION. Preserved for backwards compatibility. Set a value to the google.protobuf.Value object.
set_pb_value
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def parse_pb_value(proto: Value) -> Optional[Any]: """ DO NOT USE THIS FUNCTION. Preserved for backwards compatibility. Extract a value from the google.protobuf.Value object. """ if proto.HasField("struct_value"): return {key: parse_pb_value(val) for key, val in proto.struct_value.fields.it...
DO NOT USE THIS FUNCTION. Preserved for backwards compatibility. Extract a value from the google.protobuf.Value object.
parse_pb_value
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def dataframe_from_parsed_json(decoded_input, pandas_orient, schema=None): """Convert parsed json into pandas.DataFrame. If schema is provided this methods will attempt to cast data types according to the schema. This include base64 decoding for binary columns. Args: decoded_input: Parsed json - ei...
Convert parsed json into pandas.DataFrame. If schema is provided this methods will attempt to cast data types according to the schema. This include base64 decoding for binary columns. Args: decoded_input: Parsed json - either a list or a dictionary. pandas_orient: pandas data frame convention u...
dataframe_from_parsed_json
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def dataframe_from_raw_json(path_or_str, schema=None, pandas_orient: str = "split"): """Parse raw json into a pandas.Dataframe. If schema is provided this methods will attempt to cast data types according to the schema. This include base64 decoding for binary columns. Args: path_or_str: Path t...
Parse raw json into a pandas.Dataframe. If schema is provided this methods will attempt to cast data types according to the schema. This include base64 decoding for binary columns. Args: path_or_str: Path to a json file or a json string. schema: MLflow schema used when parsing the data. ...
dataframe_from_raw_json
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def _get_jsonable_obj(data, pandas_orient="records"): """Attempt to make the data json-able via standard library. Look for some commonly used types that are not jsonable and convert them into json-able ones. Unknown data types are returned as is. Args: data: Data to be converted, works with pa...
Attempt to make the data json-able via standard library. Look for some commonly used types that are not jsonable and convert them into json-able ones. Unknown data types are returned as is. Args: data: Data to be converted, works with pandas and numpy, rest will be returned as is. pandas_o...
_get_jsonable_obj
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def convert_data_type(data, spec): """ Convert input data to the type specified in the spec. Args: data: Input data. spec: ColSpec or TensorSpec. """ import numpy as np from mlflow.models.utils import _enforce_array, _enforce_map, _enforce_object from mlflow.types.schema im...
Convert input data to the type specified in the spec. Args: data: Input data. spec: ColSpec or TensorSpec.
convert_data_type
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def parse_inputs_data(inputs_data_or_path, schema=None): """ Helper function to cast inputs_data based on the schema. Inputs data must be able to pass to the model for pyfunc predict directly. Args: inputs_data_or_path: A json-serializable object or path to a json file schema: data sche...
Helper function to cast inputs_data based on the schema. Inputs data must be able to pass to the model for pyfunc predict directly. Args: inputs_data_or_path: A json-serializable object or path to a json file schema: data schema to cast to. Be of type `mlflow.types.Schema`.
parse_inputs_data
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def parse_tf_serving_input(inp_dict, schema=None): """ Args: inp_dict: A dict deserialized from a JSON string formatted as described in TF's serving API doc (https://www.tensorflow.org/tfx/serving/api_rest#request_format_2) schema: MLflow schema used when parsing the data...
Args: inp_dict: A dict deserialized from a JSON string formatted as described in TF's serving API doc (https://www.tensorflow.org/tfx/serving/api_rest#request_format_2) schema: MLflow schema used when parsing the data.
parse_tf_serving_input
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def dump_input_data(data, inputs_key="inputs", params: Optional[dict[str, Any]] = None): """ Args: data: Input data. inputs_key: Key to represent data in the request payload. params: Additional parameters to pass to the model for inference. """ import numpy as np import panda...
Args: data: Input data. inputs_key: Key to represent data in the request payload. params: Additional parameters to pass to the model for inference.
dump_input_data
python
mlflow/mlflow
mlflow/utils/proto_json_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/proto_json_utils.py
Apache-2.0
def model_validator(mode: str, skip_on_failure: bool = False): """A wrapper for Pydantic model validator that is compatible with Pydantic v1 and v2. Note that the `skip_on_failure` argument is only available in Pydantic v1. """ def decorator(func: Callable) -> Callable: if IS_PYDANTIC_V2_OR_NEW...
A wrapper for Pydantic model validator that is compatible with Pydantic v1 and v2. Note that the `skip_on_failure` argument is only available in Pydantic v1.
model_validator
python
mlflow/mlflow
mlflow/utils/pydantic_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/pydantic_utils.py
Apache-2.0
def model_dump_compat(pydantic_model: BaseModel, **kwargs: Any) -> dict[str, Any]: """ Dump the Pydantic model to dictionary, in a compatible way for Pydantic v1 and v2. Args: pydantic_model: The Pydantic model to dump. kwargs: Additional arguments to pass to the dump method. """ re...
Dump the Pydantic model to dictionary, in a compatible way for Pydantic v1 and v2. Args: pydantic_model: The Pydantic model to dump. kwargs: Additional arguments to pass to the dump method.
model_dump_compat
python
mlflow/mlflow
mlflow/utils/pydantic_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/pydantic_utils.py
Apache-2.0
def augmented_raise_for_status(response): """Wrap the standard `requests.response.raise_for_status()` method and return reason""" try: response.raise_for_status() except HTTPError as e: if response.text: raise HTTPError( f"{e}. Response text: {response.text}", req...
Wrap the standard `requests.response.raise_for_status()` method and return reason
augmented_raise_for_status
python
mlflow/mlflow
mlflow/utils/request_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/request_utils.py
Apache-2.0
def _cached_get_request_session( max_retries, backoff_factor, backoff_jitter, retry_codes, raise_on_status, # To create a new Session object for each process, we use the process id as the cache key. # This is to avoid sharing the same Session object across processes, which can lead to issues...
This function should not be called directly. Instead, use `_get_request_session` below.
_cached_get_request_session
python
mlflow/mlflow
mlflow/utils/request_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/request_utils.py
Apache-2.0
def _get_request_session( max_retries, backoff_factor, backoff_jitter, retry_codes, raise_on_status, respect_retry_after_header, ): """Returns a `Requests.Session` object for making an HTTP request. Args: max_retries: Maximum total number of retries. backoff_factor: A ti...
Returns a `Requests.Session` object for making an HTTP request. Args: max_retries: Maximum total number of retries. backoff_factor: A time factor for exponential backoff. e.g. value 5 means the HTTP request will be retried with interval 5, 10, 20... seconds. A value of 0 turns off the ...
_get_request_session
python
mlflow/mlflow
mlflow/utils/request_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/request_utils.py
Apache-2.0
def _get_http_response_with_retries( # noqa: D417 method, url, max_retries, backoff_factor, backoff_jitter, retry_codes, raise_on_status=True, allow_redirects=None, respect_retry_after_header=True, **kwargs, ): """Performs an HTTP request using Python's `requests` module wit...
Performs an HTTP request using Python's `requests` module with an automatic retry policy. Args: method: A string indicating the method to use, e.g. "GET", "POST", "PUT". url: The target URL address for the HTTP request. max_retries: Maximum total number of retries. backoff_factor: A...
_get_http_response_with_retries
python
mlflow/mlflow
mlflow/utils/request_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/request_utils.py
Apache-2.0
def cloud_storage_http_request( method, url, max_retries=5, backoff_factor=2, backoff_jitter=1.0, retry_codes=_TRANSIENT_FAILURE_RESPONSE_CODES, timeout=None, **kwargs, ): """Performs an HTTP PUT/GET/PATCH request using Python's `requests` module with automatic retry. Args: ...
Performs an HTTP PUT/GET/PATCH request using Python's `requests` module with automatic retry. Args: method: string of 'PUT' or 'GET' or 'PATCH', specify to do http PUT or GET or PATCH. url: the target URL address for the HTTP request. max_retries: maximum number of retries before throwing a...
cloud_storage_http_request
python
mlflow/mlflow
mlflow/utils/request_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/request_utils.py
Apache-2.0
def _parse_requirements(requirements, is_constraint, base_dir=None): """A simplified version of `pip._internal.req.parse_requirements` which performs the following operations on the given requirements file and yields the parsed requirements. - Remove comments and blank lines - Join continued lines ...
A simplified version of `pip._internal.req.parse_requirements` which performs the following operations on the given requirements file and yields the parsed requirements. - Remove comments and blank lines - Join continued lines - Resolve requirements file references (e.g. '-r requirements.txt') - Re...
_parse_requirements
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _iter_requires(name: str): """ Iterates over the requirements of the specified package. Args: name: The name of the package. Yields: The names of the required packages. """ try: reqs = importlib.metadata.requires(name) except importlib.metadata.PackageNotFoundEr...
Iterates over the requirements of the specified package. Args: name: The name of the package. Yields: The names of the required packages.
_iter_requires
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _get_requires_recursive(pkg_name, seen_before=None): """ Recursively yields both direct and transitive dependencies of the specified package. """ norm_pkg_name = _normalize_package_name(pkg_name) seen_before = seen_before or {norm_pkg_name} for req in _get_requires(pkg_name): # P...
Recursively yields both direct and transitive dependencies of the specified package.
_get_requires_recursive
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _prune_packages(packages): """ Prunes packages required by other packages. For example, `["scikit-learn", "numpy"]` is pruned to `["scikit-learn"]`. """ packages = set(packages) requires = set(_flatten(map(_get_requires_recursive, packages))) # LlamaIndex have one root "llama-index" pac...
Prunes packages required by other packages. For example, `["scikit-learn", "numpy"]` is pruned to `["scikit-learn"]`.
_prune_packages
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _run_command(cmd, timeout_seconds, env=None): """ Runs the specified command. If it exits with non-zero status, `MlflowException` is raised. """ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) timer = Timer(timeout_seconds, proc.kill) try: timer....
Runs the specified command. If it exits with non-zero status, `MlflowException` is raised.
_run_command
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _get_installed_version(package: str, module: Optional[str] = None) -> str: """ Obtains the installed package version using `importlib_metadata.version`. If it fails, use `__import__(module or package).__version__`. """ if package == "mlflow": # `importlib.metadata.version` may return an ...
Obtains the installed package version using `importlib_metadata.version`. If it fails, use `__import__(module or package).__version__`.
_get_installed_version
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _capture_imported_modules(model_uri, flavor, record_full_module=False, extra_env_vars=None): """Runs `_capture_modules.py` in a subprocess and captures modules imported during the model loading procedure. If flavor is `transformers`, `_capture_transformers_modules.py` is run instead. Args: ...
Runs `_capture_modules.py` in a subprocess and captures modules imported during the model loading procedure. If flavor is `transformers`, `_capture_transformers_modules.py` is run instead. Args: model_uri: The URI of the model. flavor: The flavor name of the model. record_full_modul...
_capture_imported_modules
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _infer_requirements(model_uri, flavor, raise_on_error=False, extra_env_vars=None): """Infers the pip requirements of the specified model by creating a subprocess and loading the model in it to determine which packages are imported. Args: model_uri: The URI of the model. flavor: The flav...
Infers the pip requirements of the specified model by creating a subprocess and loading the model in it to determine which packages are imported. Args: model_uri: The URI of the model. flavor: The flavor name of the model. raise_on_error: If True, raise an exception if an unrecognized p...
_infer_requirements
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _get_local_version_label(version): """Extracts a local version label from `version`. Args: version: A version string. """ try: return Version(version).local except InvalidVersion: return None
Extracts a local version label from `version`. Args: version: A version string.
_get_local_version_label
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _strip_local_version_label(version): """Strips a local version label in `version`. Local version identifiers: https://www.python.org/dev/peps/pep-0440/#local-version-identifiers Args: version: A version string to strip. """ class IgnoreLocal(Version): @property def...
Strips a local version label in `version`. Local version identifiers: https://www.python.org/dev/peps/pep-0440/#local-version-identifiers Args: version: A version string to strip.
_strip_local_version_label
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _get_pinned_requirement(req_str, version=None, module=None): """Returns a string representing a pinned pip requirement to install the specified package and version (e.g. 'mlflow==1.2.3'). Args: req_str: The package requirement string (e.g. "mlflow" or "mlflow[gateway]"). version: The ve...
Returns a string representing a pinned pip requirement to install the specified package and version (e.g. 'mlflow==1.2.3'). Args: req_str: The package requirement string (e.g. "mlflow" or "mlflow[gateway]"). version: The version of the package. If None, defaults to the installed version. ...
_get_pinned_requirement
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def _check_requirement_satisfied(requirement_str): """ Checks whether the current python environment satisfies the given requirement if it is parsable as a package name and a set of version specifiers, and returns a `_MismatchedPackageInfo` object containing the mismatched package name, installed versio...
Checks whether the current python environment satisfies the given requirement if it is parsable as a package name and a set of version specifiers, and returns a `_MismatchedPackageInfo` object containing the mismatched package name, installed version, and requirement if the requirement is not satisfied...
_check_requirement_satisfied
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def warn_dependency_requirement_mismatches(model_requirements: list[str]): """ Inspects the model's dependencies and prints a warning if the current Python environment doesn't satisfy them. """ # Suppress databricks-feature-lookup warning for feature store cases # Suppress databricks-chains, dat...
Inspects the model's dependencies and prints a warning if the current Python environment doesn't satisfy them.
warn_dependency_requirement_mismatches
python
mlflow/mlflow
mlflow/utils/requirements_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/requirements_utils.py
Apache-2.0
def http_request_safe(host_creds, endpoint, method, **kwargs): """ Wrapper around ``http_request`` that also verifies that the request succeeds with code 200. """ response = http_request(host_creds=host_creds, endpoint=endpoint, method=method, **kwargs) return verify_rest_response(response, endpoint...
Wrapper around ``http_request`` that also verifies that the request succeeds with code 200.
http_request_safe
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def verify_rest_response(response, endpoint): """Verify the return code and format, raise exception if the request was not successful.""" # Handle Armeria-specific response case where response text is "200 OK" if response.status_code == 200 and response.text.strip() == _ARMERIA_OK: response._content...
Verify the return code and format, raise exception if the request was not successful.
verify_rest_response
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def _retry_databricks_sdk_call_with_exponential_backoff( *, call_func: Callable, retry_codes: list[int], retry_timeout_seconds: int, backoff_factor: int, backoff_jitter: float, max_retries: int, ): """ Retry a Databricks SDK call with exponential backoff until timeout or max retries ...
Retry a Databricks SDK call with exponential backoff until timeout or max retries reached. Args: call_func: Function to call that may raise DatabricksError retry_codes: Set of HTTP status codes that should trigger retries retry_timeout_seconds: Maximum time to spend retrying in seconds...
_retry_databricks_sdk_call_with_exponential_backoff
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def extract_api_info_for_service(service, path_prefix): """Return a dictionary mapping each API method to a tuple (path, HTTP method)""" service_methods = service.DESCRIPTOR.methods res = {} for service_method in service_methods: endpoints = service_method.GetOptions().Extensions[databricks_pb2....
Return a dictionary mapping each API method to a tuple (path, HTTP method)
extract_api_info_for_service
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def extract_all_api_info_for_service(service, path_prefix): """Return a dictionary mapping each API method to a list of tuples [(path, HTTP method)]""" service_methods = service.DESCRIPTOR.methods res = {} for service_method in service_methods: endpoints = service_method.GetOptions().Extensions[...
Return a dictionary mapping each API method to a list of tuples [(path, HTTP method)]
extract_all_api_info_for_service
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def get_single_trace_endpoint(request_id, use_v3=False): """ Get the endpoint for a single trace. For Databricks tracking URIs, use the V3 API. For all other tracking URIs, use the V2 API. Args: request_id: The trace ID. use_v3: Whether to use the V3 API. If True, use the V3 API. If...
Get the endpoint for a single trace. For Databricks tracking URIs, use the V3 API. For all other tracking URIs, use the V2 API. Args: request_id: The trace ID. use_v3: Whether to use the V3 API. If True, use the V3 API. If False, use the V2 API.
get_single_trace_endpoint
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def get_create_assessment_endpoint(trace_id: str, is_databricks=False): """ Get the endpoint for creating an assessment. Args: trace_id: The trace ID. is_databricks: Whether the tracking URI is a Databricks URI. """ if is_databricks: return f"{_V3_TRACE_REST_API_PATH_PREFIX}...
Get the endpoint for creating an assessment. Args: trace_id: The trace ID. is_databricks: Whether the tracking URI is a Databricks URI.
get_create_assessment_endpoint
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def get_single_assessment_endpoint(trace_id: str, assessment_id: str, is_databricks=False): """ Get the endpoint for a single assessment. Args: trace_id: The trace ID. assessment_id: The assessment ID. is_databricks: Whether the tracking URI is a Databricks URI. """ if is_da...
Get the endpoint for a single assessment. Args: trace_id: The trace ID. assessment_id: The assessment ID. is_databricks: Whether the tracking URI is a Databricks URI.
get_single_assessment_endpoint
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def get_search_traces_v3_endpoint(is_databricks=False): """ Return the endpoint for the SearchTraces API. Args: is_databricks: Whether the tracking URI is a Databricks URI. If True, returns the v3 endpoint, otherwise returns the v2 endpoint. """ if is_databricks: ...
Return the endpoint for the SearchTraces API. Args: is_databricks: Whether the tracking URI is a Databricks URI. If True, returns the v3 endpoint, otherwise returns the v2 endpoint.
get_search_traces_v3_endpoint
python
mlflow/mlflow
mlflow/utils/rest_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/rest_utils.py
Apache-2.0
def is_numeric(self) -> bool: """ Does this entity represent a numeric column? """ return self.type == EntityType.METRIC or ( self.type == EntityType.ATTRIBUTE and SqlLoggedModel.is_numeric(self.key) )
Does this entity represent a numeric column?
is_numeric
python
mlflow/mlflow
mlflow/utils/search_logged_model_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_logged_model_utils.py
Apache-2.0
def _join_in_comparison_tokens(tokens, search_traces=False): """ Find a sequence of tokens that matches the pattern of an IN comparison or a NOT IN comparison, join the tokens into a single Comparison token. Otherwise, return the original list of tokens. """ if Version(sqlparse.__version__) < Versio...
Find a sequence of tokens that matches the pattern of an IN comparison or a NOT IN comparison, join the tokens into a single Comparison token. Otherwise, return the original list of tokens.
_join_in_comparison_tokens
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _trim_backticks(cls, entity_type): """Remove backticks from identifier like `param`, if they exist.""" if cls._is_quoted(entity_type, "`"): return cls._trim_ends(entity_type) return entity_type
Remove backticks from identifier like `param`, if they exist.
_trim_backticks
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _strip_quotes(cls, value, expect_quoted_value=False): """ Remove quotes for input string. Values of type strings are expected to have quotes. Keys containing special characters are also expected to be enclose in quotes. """ if cls._is_quoted(value, "'") or cls._is_quo...
Remove quotes for input string. Values of type strings are expected to have quotes. Keys containing special characters are also expected to be enclose in quotes.
_strip_quotes
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def filter(cls, runs, filter_string): """Filters a set of runs based on a search filter string.""" if not filter_string: return runs parsed = cls.parse_search_filter(filter_string) def run_matches(run): return all(cls._does_run_match_clause(run, s) for s in parse...
Filters a set of runs based on a search filter string.
filter
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _get_value_for_sort(cls, run, key_type, key, ascending): """Returns a tuple suitable to be used as a sort key for runs.""" sort_value = None key = SearchUtils.translate_key_alias(key) if key_type == cls._METRIC_IDENTIFIER: sort_value = run.data.metrics.get(key) el...
Returns a tuple suitable to be used as a sort key for runs.
_get_value_for_sort
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _get_model_value_for_sort(cls, model, key_type, key, ascending): """Returns a tuple suitable to be used as a sort key for models.""" sort_value = None key = SearchUtils.translate_key_alias(key) if key_type == cls._METRIC_IDENTIFIER: matching_metrics = [metric for metric i...
Returns a tuple suitable to be used as a sort key for models.
_get_model_value_for_sort
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def sort(cls, runs, order_by_list): """Sorts a set of runs based on their natural ordering and an overriding set of order_bys. Runs are naturally ordered first by start time descending, then by run id for tie-breaking. """ runs = sorted(runs, key=lambda run: (-run.info.start_time, run.in...
Sorts a set of runs based on their natural ordering and an overriding set of order_bys. Runs are naturally ordered first by start time descending, then by run id for tie-breaking.
sort
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _check_valid_identifier_list(cls, tup: tuple[Any, ...]) -> None: """ Validate that `tup` is a non-empty tuple of strings. """ if len(tup) == 0: raise MlflowException( "While parsing a list in the query," " expected a non-empty list of strin...
Validate that `tup` is a non-empty tuple of strings.
_check_valid_identifier_list
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def filter(cls, registered_models, filter_string): """Filters a set of registered models based on a search filter string.""" if not filter_string: return registered_models parsed = cls.parse_search_filter(filter_string) def registered_model_matches(model): return...
Filters a set of registered models based on a search filter string.
filter
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def filter(cls, model_versions, filter_string): """Filters a set of model versions based on a search filter string.""" model_versions = [mv for mv in model_versions if mv.current_stage != STAGE_DELETED_INTERNAL] if not filter_string: return model_versions parsed = cls.parse_s...
Filters a set of model versions based on a search filter string.
filter
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def filter(cls, traces, filter_string): """Filters a set of traces based on a search filter string.""" if not filter_string: return traces parsed = cls.parse_search_filter_for_search_traces(filter_string) def trace_matches(trace): return all(cls._does_trace_match...
Filters a set of traces based on a search filter string.
filter
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _replace_key_to_tag_or_metadata(cls, parsed: dict[str, Any]): """ Replace search key to tag or metadata key if it is in the mapping. """ key = parsed.get("key").lower() if key in cls.SEARCH_KEY_TO_TAG: parsed["type"] = cls._TAG_IDENTIFIER parsed["key"]...
Replace search key to tag or metadata key if it is in the mapping.
_replace_key_to_tag_or_metadata
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def validate_list_supported(cls, key: str) -> None: """ Override to allow logged model attributes to be used with IN/NOT IN. """
Override to allow logged model attributes to be used with IN/NOT IN.
validate_list_supported
python
mlflow/mlflow
mlflow/utils/search_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/search_utils.py
Apache-2.0
def _create_table( rows: list[list[str]], headers: list[str], column_sep: str = " " * 2, min_column_width: int = 4 ) -> str: """ Creates a table from a list of rows and headers. Example ======= >>> print(_create_table([["a", "b", "c"], ["d", "e", "f"]], ["x", "y", "z"])) x y z -...
Creates a table from a list of rows and headers. Example ======= >>> print(_create_table([["a", "b", "c"], ["d", "e", "f"]], ["x", "y", "z"])) x y z ---- ---- ---- a b c d e f
_create_table
python
mlflow/mlflow
mlflow/utils/string_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/string_utils.py
Apache-2.0
def mslex_quote(s, for_cmd=True): """ Quote a string for use as a command line argument in DOS or Windows. On windows, before a command line argument becomes a char* in a program's argv, it must be parsed by both cmd.exe, and by CommandLineToArgvW. If for_cmd is true, then this will quote the ...
Quote a string for use as a command line argument in DOS or Windows. On windows, before a command line argument becomes a char* in a program's argv, it must be parsed by both cmd.exe, and by CommandLineToArgvW. If for_cmd is true, then this will quote the string so it will be parsed correctly...
mslex_quote
python
mlflow/mlflow
mlflow/utils/string_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/string_utils.py
Apache-2.0
def get(self): """ Get the thread-local variable value. If the thread-local variable is not set, return the provided `init_value` value. If `get` is called in a forked subprocess and `reset_in_subprocess` is True, return the provided `init_value` value """ if hasa...
Get the thread-local variable value. If the thread-local variable is not set, return the provided `init_value` value. If `get` is called in a forked subprocess and `reset_in_subprocess` is True, return the provided `init_value` value
get
python
mlflow/mlflow
mlflow/utils/thread_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/thread_utils.py
Apache-2.0
def set(self, value): """ Set a value for the thread-local variable. """ self.thread_local.value = (value, os.getpid()) self.__global_thread_values[threading.get_ident()] = value
Set a value for the thread-local variable.
set
python
mlflow/mlflow
mlflow/utils/thread_utils.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/thread_utils.py
Apache-2.0
def run_with_timeout(seconds): """ Context manager to runs a block of code with a timeout. If the block of code takes longer than `seconds` to execute, a `TimeoutError` is raised. NB: This function uses Unix signals to implement the timeout, so it is not thread-safe. Also it does not work on non-Uni...
Context manager to runs a block of code with a timeout. If the block of code takes longer than `seconds` to execute, a `TimeoutError` is raised. NB: This function uses Unix signals to implement the timeout, so it is not thread-safe. Also it does not work on non-Unix platforms such as Windows. E.g....
run_with_timeout
python
mlflow/mlflow
mlflow/utils/timeout.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/timeout.py
Apache-2.0
def is_local_uri(uri, is_tracking_or_registry_uri=True): """Returns true if the specified URI is a local file path (/foo or file:/foo). Args: uri: The URI. is_tracking_or_registry_uri: Whether or not the specified URI is an MLflow Tracking or MLflow Model Registry URI. Examples of o...
Returns true if the specified URI is a local file path (/foo or file:/foo). Args: uri: The URI. is_tracking_or_registry_uri: Whether or not the specified URI is an MLflow Tracking or MLflow Model Registry URI. Examples of other URIs are MLflow artifact URIs, filesystem paths...
is_local_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def is_databricks_uri(uri): """ Databricks URIs look like 'databricks' (default profile) or 'databricks://profile' or 'databricks://secret_scope:secret_key_prefix'. """ scheme = urllib.parse.urlparse(uri).scheme return scheme == "databricks" or uri == "databricks"
Databricks URIs look like 'databricks' (default profile) or 'databricks://profile' or 'databricks://secret_scope:secret_key_prefix'.
is_databricks_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def is_fuse_or_uc_volumes_uri(uri): """ Validates whether a provided URI is directed to a FUSE mount point or a UC volumes mount point. Multiple directory paths are collapsed into a single designator for root path validation. For example, "////Volumes/" will resolve to "/Volumes/" for validation purpose...
Validates whether a provided URI is directed to a FUSE mount point or a UC volumes mount point. Multiple directory paths are collapsed into a single designator for root path validation. For example, "////Volumes/" will resolve to "/Volumes/" for validation purposes.
is_fuse_or_uc_volumes_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def construct_db_uc_uri_from_profile(profile): """ Construct a databricks-uc URI from a profile. Args: profile: The profile name, optionally with key_prefix (e.g., "profile" or "scope:key") Returns: A databricks-uc URI string, or the scheme alone if no profile is provided """ i...
Construct a databricks-uc URI from a profile. Args: profile: The profile name, optionally with key_prefix (e.g., "profile" or "scope:key") Returns: A databricks-uc URI string, or the scheme alone if no profile is provided
construct_db_uc_uri_from_profile
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def get_db_info_from_uri(uri): """ Get the Databricks profile specified by the tracking URI (if any), otherwise returns None. """ parsed_uri = urllib.parse.urlparse(uri) if parsed_uri.scheme == "databricks" or parsed_uri.scheme == _DATABRICKS_UNITY_CATALOG_SCHEME: # netloc should not be ...
Get the Databricks profile specified by the tracking URI (if any), otherwise returns None.
get_db_info_from_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def get_databricks_profile_uri_from_artifact_uri(uri, result_scheme="databricks"): """ Retrieves the netloc portion of the URI as a ``databricks://`` or `databricks-uc://` URI, if it is a proper Databricks profile specification, e.g. ``profile@databricks`` or ``secret_scope:key_prefix@databricks``. ...
Retrieves the netloc portion of the URI as a ``databricks://`` or `databricks-uc://` URI, if it is a proper Databricks profile specification, e.g. ``profile@databricks`` or ``secret_scope:key_prefix@databricks``.
get_databricks_profile_uri_from_artifact_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def remove_databricks_profile_info_from_artifact_uri(artifact_uri): """ Only removes the netloc portion of the URI if it is a Databricks profile specification, e.g. ``profile@databricks`` or ``secret_scope:key_prefix@databricks``. """ parsed = urllib.parse.urlparse(artifact_uri) if not parse...
Only removes the netloc portion of the URI if it is a Databricks profile specification, e.g. ``profile@databricks`` or ``secret_scope:key_prefix@databricks``.
remove_databricks_profile_info_from_artifact_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def add_databricks_profile_info_to_artifact_uri(artifact_uri, databricks_profile_uri): """ Throws an exception if ``databricks_profile_uri`` is not valid. """ if not databricks_profile_uri or not is_databricks_uri(databricks_profile_uri): return artifact_uri artifact_uri_parsed = urllib.pars...
Throws an exception if ``databricks_profile_uri`` is not valid.
add_databricks_profile_info_to_artifact_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def extract_db_type_from_uri(db_uri): """ Parse the specified DB URI to extract the database type. Confirm the database type is supported. If a driver is specified, confirm it passes a plausible regex. """ scheme = urllib.parse.urlparse(db_uri).scheme scheme_plus_count = scheme.count("+") i...
Parse the specified DB URI to extract the database type. Confirm the database type is supported. If a driver is specified, confirm it passes a plausible regex.
extract_db_type_from_uri
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def append_to_uri_path(uri, *paths): """Appends the specified POSIX `paths` to the path component of the specified `uri`. Args: uri: The input URI, represented as a string. paths: The POSIX paths to append to the specified `uri`'s path component. Returns: A new URI with a path comp...
Appends the specified POSIX `paths` to the path component of the specified `uri`. Args: uri: The input URI, represented as a string. paths: The POSIX paths to append to the specified `uri`'s path component. Returns: A new URI with a path component consisting of the specified `paths` ap...
append_to_uri_path
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def append_to_uri_query_params(uri, *query_params: tuple[str, Any]) -> str: """Appends the specified query parameters to an existing URI. Args: uri: The URI to which to append query parameters. query_params: Query parameters to append. Each parameter should be a 2-element tuple. For...
Appends the specified query parameters to an existing URI. Args: uri: The URI to which to append query parameters. query_params: Query parameters to append. Each parameter should be a 2-element tuple. For example, ``("key", "value")``.
append_to_uri_query_params
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def _join_posixpaths_and_append_absolute_suffixes(prefix_path, suffix_path): """ Joins the POSIX path `prefix_path` with the POSIX path `suffix_path`. Unlike posixpath.join(), if `suffix_path` is an absolute path, it is appended to prefix_path. >>> result1 = _join_posixpaths_and_append_absolute_suffixe...
Joins the POSIX path `prefix_path` with the POSIX path `suffix_path`. Unlike posixpath.join(), if `suffix_path` is an absolute path, it is appended to prefix_path. >>> result1 = _join_posixpaths_and_append_absolute_suffixes("relpath1", "relpath2") >>> assert result1 == "relpath1/relpath2" >>> resu...
_join_posixpaths_and_append_absolute_suffixes
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def dbfs_hdfs_uri_to_fuse_path(dbfs_uri): """Converts the provided DBFS URI into a DBFS FUSE path Args: dbfs_uri: A DBFS URI like "dbfs:/my-directory". Can also be a scheme-less URI like "/my-directory" if running in an environment where the default HDFS filesystem is "dbfs:/" (...
Converts the provided DBFS URI into a DBFS FUSE path Args: dbfs_uri: A DBFS URI like "dbfs:/my-directory". Can also be a scheme-less URI like "/my-directory" if running in an environment where the default HDFS filesystem is "dbfs:/" (e.g. Databricks) Returns: A DBFS FUS...
dbfs_hdfs_uri_to_fuse_path
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def resolve_uri_if_local(local_uri): """ if `local_uri` is passed in as a relative local path, this function resolves it to absolute path relative to current working directory. Args: local_uri: Relative or absolute path or local file uri Returns: a fully-formed absolute uri path or...
if `local_uri` is passed in as a relative local path, this function resolves it to absolute path relative to current working directory. Args: local_uri: Relative or absolute path or local file uri Returns: a fully-formed absolute uri path or an absolute filesystem path
resolve_uri_if_local
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def validate_path_is_safe(path): """ Validates that the specified path is safe to join with a trusted prefix. This is a security measure to prevent path traversal attacks. A valid path should: not contain separators other than '/' not contain .. to navigate to parent dir in path ...
Validates that the specified path is safe to join with a trusted prefix. This is a security measure to prevent path traversal attacks. A valid path should: not contain separators other than '/' not contain .. to navigate to parent dir in path not be an absolute path
validate_path_is_safe
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def strip_scheme(uri: str) -> str: """ Strips the scheme from the specified URI. Example: >>> strip_scheme("http://example.com") '//example.com' """ parsed = urllib.parse.urlparse(uri) # `_replace` looks like a private method, but it's actually part of the public API: # https://doc...
Strips the scheme from the specified URI. Example: >>> strip_scheme("http://example.com") '//example.com'
strip_scheme
python
mlflow/mlflow
mlflow/utils/uri.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/uri.py
Apache-2.0
def invalid_value(path, value, message=None): """ Compose a standardized error message for invalid parameter values. """ formattedValue = json.dumps(value, sort_keys=True, separators=(",", ":")) if message: return f"Invalid value {formattedValue} for parameter '{path}' supplied: {message}" ...
Compose a standardized error message for invalid parameter values.
invalid_value
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_metric_name(name, path="name"): """Check that `name` is a valid metric name and raise an exception if it isn't.""" if name is None: raise MlflowException( invalid_value(path, name, f"Metric name cannot be None. {_MISSING_KEY_NAME_MESSAGE}"), error_code=INVALID_PARAM...
Check that `name` is a valid metric name and raise an exception if it isn't.
_validate_metric_name
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _is_numeric(value): """ Returns True if the passed-in value is numeric. """ # Note that `isinstance(bool_value, numbers.Number)` returns `True` because `bool` is a # subclass of `int`. return not isinstance(value, bool) and isinstance(value, numbers.Number)
Returns True if the passed-in value is numeric.
_is_numeric
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_metric(key, value, timestamp, step, path=""): """ Check that a metric with the specified key, value, timestamp, and step is valid and raise an exception if it isn't. """ _validate_metric_name(key, append_to_json_path(path, "name")) # If invocated via log_metric, no prior validatio...
Check that a metric with the specified key, value, timestamp, and step is valid and raise an exception if it isn't.
_validate_metric
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_param(key, value, path=""): """ Check that a param with the specified key & value is valid and raise an exception if it isn't. """ _validate_param_name(key, append_to_json_path(path, "key")) return Param( _validate_length_limit("Param key", MAX_ENTITY_KEY_LENGTH, key), ...
Check that a param with the specified key & value is valid and raise an exception if it isn't.
_validate_param
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_tag(key, value, path=""): """ Check that a tag with the specified key & value is valid and raise an exception if it isn't. """ _validate_tag_name(key, append_to_json_path(path, "key")) return RunTag( _validate_length_limit(append_to_json_path(path, "key"), MAX_ENTITY_KEY_LENGTH...
Check that a tag with the specified key & value is valid and raise an exception if it isn't.
_validate_tag
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_param_keys_unique(params): """Ensures that duplicate param keys are not present in the `log_batch()` params argument""" unique_keys = [] dupe_keys = [] for param in params: if param.key not in unique_keys: unique_keys.append(param.key) else: dupe_key...
Ensures that duplicate param keys are not present in the `log_batch()` params argument
_validate_param_keys_unique
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_param_name(name, path="key"): """Check that `name` is a valid parameter name and raise an exception if it isn't.""" if name is None: raise MlflowException( invalid_value(path, "", _MISSING_KEY_NAME_MESSAGE), error_code=INVALID_PARAMETER_VALUE, ) if not v...
Check that `name` is a valid parameter name and raise an exception if it isn't.
_validate_param_name
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_tag_name(name, path="key"): """Check that `name` is a valid tag name and raise an exception if it isn't.""" # Reuse param & metric check. if name is None: raise MlflowException( missing_value(path), error_code=INVALID_PARAMETER_VALUE, ) if not valida...
Check that `name` is a valid tag name and raise an exception if it isn't.
_validate_tag_name
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_run_id(run_id, path="run_id"): """Check that `run_id` is a valid run ID and raise an exception if it isn't.""" if _RUN_ID_REGEX.match(run_id) is None: raise MlflowException(invalid_value(path, run_id), error_code=INVALID_PARAMETER_VALUE)
Check that `run_id` is a valid run ID and raise an exception if it isn't.
_validate_run_id
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_experiment_id(exp_id): """Check that `experiment_id`is a valid string or None, raise an exception if it isn't.""" if exp_id is not None and _EXPERIMENT_ID_REGEX.match(exp_id) is None: raise MlflowException( f"Invalid experiment ID: '{exp_id}'", error_code=INVALID_PARAMETER_VALU...
Check that `experiment_id`is a valid string or None, raise an exception if it isn't.
_validate_experiment_id
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_experiment_name(experiment_name): """Check that `experiment_name` is a valid string and raise an exception if it isn't.""" if experiment_name == "" or experiment_name is None: raise MlflowException( f"Invalid experiment name: '{experiment_name}'", error_code=INVALID...
Check that `experiment_name` is a valid string and raise an exception if it isn't.
_validate_experiment_name
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_experiment_id_type(experiment_id): """ Check that a user-provided experiment_id is either a string, int, or None and raise an exception if it isn't. """ if experiment_id is not None and not isinstance(experiment_id, (str, int)): raise MlflowException( f"Invalid expe...
Check that a user-provided experiment_id is either a string, int, or None and raise an exception if it isn't.
_validate_experiment_id_type
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_db_type_string(db_type): """validates db_type parsed from DB URI is supported""" from mlflow.store.db.db_types import DATABASE_ENGINES if db_type not in DATABASE_ENGINES: error_msg = ( f"Invalid database engine: '{db_type}'. " f"Supported database engines are {...
validates db_type parsed from DB URI is supported
_validate_db_type_string
python
mlflow/mlflow
mlflow/utils/validation.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py
Apache-2.0
def _validate_pyenv_is_available(): """ Validates pyenv is available. If not, throws an `MlflowException` with a brief instruction on how to install pyenv. """ url = ( "https://github.com/pyenv/pyenv#installation" if not is_windows() else "https://github.com/pyenv-win/pyenv-w...
Validates pyenv is available. If not, throws an `MlflowException` with a brief instruction on how to install pyenv.
_validate_pyenv_is_available
python
mlflow/mlflow
mlflow/utils/virtualenv.py
https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py
Apache-2.0