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 _use_repl_context_if_available(
name: str,
*,
ignore_none: bool = False,
):
"""Creates a decorator to insert a short circuit that returns the specified REPL context
attribute if it's available.
Args:
name: Attribute name (e.g. "apiUrl").
ignore_none: If True, use the origina... | Creates a decorator to insert a short circuit that returns the specified REPL context
attribute if it's available.
Args:
name: Attribute name (e.g. "apiUrl").
ignore_none: If True, use the original function if the REPL context attribute exists but
is None.
Returns:
Deco... | _use_repl_context_if_available | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def is_in_databricks_model_serving_environment():
"""
Check if the code is running in Databricks Model Serving environment.
The environment variable set by Databricks when starting the serving container.
"""
val = (
os.environ.get("IS_IN_DB_MODEL_SERVING_ENV")
# Checking the old env ... |
Check if the code is running in Databricks Model Serving environment.
The environment variable set by Databricks when starting the serving container.
| is_in_databricks_model_serving_environment | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def is_databricks_connect(spark=None):
"""
Return True if current Spark-connect client connects to Databricks cluster.
"""
from mlflow.utils.spark_utils import is_spark_connect_mode
if is_in_databricks_serverless_runtime() or is_in_databricks_shared_cluster_runtime():
return True
spark... |
Return True if current Spark-connect client connects to Databricks cluster.
| is_databricks_connect | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_dbconnect_udf_sandbox_info(spark):
"""
Get Databricks UDF sandbox info which includes the following fields:
- image_version like
'{major_version}.{minor_version}' or 'client.{major_version}.{minor_version}'
- runtime_version like '{major_version}.{minor_version}'
- platform_machine ... |
Get Databricks UDF sandbox info which includes the following fields:
- image_version like
'{major_version}.{minor_version}' or 'client.{major_version}.{minor_version}'
- runtime_version like '{major_version}.{minor_version}'
- platform_machine like 'x86_64' or 'aarch64'
- mlflow_version
... | get_dbconnect_udf_sandbox_info | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def is_databricks_serverless(spark):
"""
Return True if running on Databricks Serverless notebook or
on Databricks Connect client that connects to Databricks Serverless.
"""
from mlflow.utils.spark_utils import is_spark_connect_mode
if not is_spark_connect_mode():
return False
if h... |
Return True if running on Databricks Serverless notebook or
on Databricks Connect client that connects to Databricks Serverless.
| is_databricks_serverless | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_notebook_id():
"""Should only be called if is_in_databricks_notebook is true"""
if notebook_id := _get_property_from_spark_context("spark.databricks.notebook.id"):
return notebook_id
if (path := acl_path_of_acl_root()) and path.startswith("/workspace"):
return path.split("/")[-1]
... | Should only be called if is_in_databricks_notebook is true | get_notebook_id | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_repl_id():
"""
Returns:
The ID of the current Databricks Python REPL.
"""
# Attempt to fetch the REPL ID from the Python REPL's entrypoint object. This REPL ID
# is guaranteed to be set upon REPL startup in DBR / MLR 9.0
try:
dbutils = _get_dbutils()
repl_id = dbu... |
Returns:
The ID of the current Databricks Python REPL.
| get_repl_id | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_job_type():
"""Should only be called if is_in_databricks_job is true"""
try:
return _get_command_context().jobTaskType().get()
except Exception:
return _get_context_tag("jobTaskType") | Should only be called if is_in_databricks_job is true | get_job_type | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_webapp_url():
"""Should only be called if is_in_databricks_notebook or is_in_databricks_jobs is true"""
url = _get_property_from_spark_context("spark.databricks.api.url")
if url is not None:
return url
try:
return _get_command_context().apiUrl().get()
except Exception:
... | Should only be called if is_in_databricks_notebook or is_in_databricks_jobs is true | get_webapp_url | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_databricks_host_creds(server_uri=None):
"""
Reads in configuration necessary to make HTTP requests to a Databricks server. This
uses Databricks SDK workspace client API,
If no available credential configuration is found to the server URI, this function
will attempt to retrieve these credenti... |
Reads in configuration necessary to make HTTP requests to a Databricks server. This
uses Databricks SDK workspace client API,
If no available credential configuration is found to the server URI, this function
will attempt to retrieve these credentials from the Databricks Secret Manager. For that to wor... | get_databricks_host_creds | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_databricks_run_url(tracking_uri: str, run_id: str, artifact_path=None) -> Optional[str]:
"""
Obtains a Databricks URL corresponding to the specified MLflow Run, optionally referring
to an artifact within the run.
Args:
tracking_uri: The URI of the MLflow Tracking server containing the R... |
Obtains a Databricks URL corresponding to the specified MLflow Run, optionally referring
to an artifact within the run.
Args:
tracking_uri: The URI of the MLflow Tracking server containing the Run.
run_id: The ID of the MLflow Run for which to obtain a Databricks URL.
artifact_path... | get_databricks_run_url | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def get_databricks_model_version_url(registry_uri: str, name: str, version: str) -> Optional[str]:
"""Obtains a Databricks URL corresponding to the specified Model Version.
Args:
registry_uri: The URI of the Model Registry server containing the Model Version.
name: The name of the registered mo... | Obtains a Databricks URL corresponding to the specified Model Version.
Args:
registry_uri: The URI of the Model Registry server containing the Model Version.
name: The name of the registered model containing the Model Version.
version: Version number of the Model Version.
Returns:
... | get_databricks_model_version_url | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def _construct_databricks_logged_model_url(
workspace_url: str, experiment_id: str, model_id: str, workspace_id: Optional[str] = None
) -> str:
"""
Get a Databricks URL for a given registered model version in Unity Catalog.
Args:
workspace_url: The URL of the workspace the registered model is i... |
Get a Databricks URL for a given registered model version in Unity Catalog.
Args:
workspace_url: The URL of the workspace the registered model is in.
experiment_id: The ID of the experiment the model is logged to.
model_id: The ID of the logged model to create the URL for.
work... | _construct_databricks_logged_model_url | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def _construct_databricks_uc_registered_model_url(
workspace_url: str, registered_model_name: str, version: str, workspace_id: Optional[str] = None
) -> str:
"""
Get a Databricks URL for a given registered model version in Unity Catalog.
Args:
workspace_url: The URL of the workspace the registe... |
Get a Databricks URL for a given registered model version in Unity Catalog.
Args:
workspace_url: The URL of the workspace the registered model is in.
registered_model_name: The full name of the registered model containing the version.
version: The version of the registered model to cre... | _construct_databricks_uc_registered_model_url | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def _get_databricks_serverless_env_vars() -> dict[str, str]:
"""
Returns the environment variables required to to initialize WorkspaceClient in a subprocess
with serverless compute.
Note:
Databricks authentication related environment variables such as DATABRICKS_HOST are
set in the are ... |
Returns the environment variables required to to initialize WorkspaceClient in a subprocess
with serverless compute.
Note:
Databricks authentication related environment variables such as DATABRICKS_HOST are
set in the are set in the _capture_imported_modules function.
| _get_databricks_serverless_env_vars | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def _init_databricks_dynamic_token_config_provider(entry_point):
"""
set a custom DatabricksConfigProvider with the hostname and token of the
user running the current command (achieved by looking at
PythonAccessibleThreadLocals.commandContext, via the already-exposed
NotebookUtils.getContext API)
... |
set a custom DatabricksConfigProvider with the hostname and token of the
user running the current command (achieved by looking at
PythonAccessibleThreadLocals.commandContext, via the already-exposed
NotebookUtils.getContext API)
| _init_databricks_dynamic_token_config_provider | python | mlflow/mlflow | mlflow/utils/databricks_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/databricks_utils.py | Apache-2.0 |
def _indent(text: str, indent: str) -> str:
"""Indent everything but first line in text."""
lines = text.splitlines()
if len(lines) <= 1:
return text
else:
first_line = lines[0]
subsequent_lines = "\n".join(list(lines[1:]))
indented_subsequent_lines = textwrap.indent(sub... | Indent everything but first line in text. | _indent | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def _replace_all(text: str, replacements: dict[str, str]) -> str:
"""
Replace all instances of replacements.keys() with their corresponding
values in text. The replacements will be inserted on the same line
with wrapping to the same level of indentation, for example:
```
Args:
param_1: ... |
Replace all instances of replacements.keys() with their corresponding
values in text. The replacements will be inserted on the same line
with wrapping to the same level of indentation, for example:
```
Args:
param_1: {{ key }}
```
will become...
```
Args:
param_1:... | _replace_all | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def format(self, **kwargs):
"""
Formats values to be substituted in via the format_docstring() method.
Args:
kwargs: A `dict` in the form of `{"< placeholder name >": "< value >"}`.
Returns:
A new `ParamDocs` instance with the formatted param docs.
.. c... |
Formats values to be substituted in via the format_docstring() method.
Args:
kwargs: A `dict` in the form of `{"< placeholder name >": "< value >"}`.
Returns:
A new `ParamDocs` instance with the formatted param docs.
.. code-block:: text
:caption: ... | format | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def format_docstring(self, docstring: str) -> str:
"""
Formats placeholders in `docstring`.
Args:
docstring: A docstring with placeholders to be replaced.
If provided with None, will return None.
.. code-block:: text
:caption: Example
... |
Formats placeholders in `docstring`.
Args:
docstring: A docstring with placeholders to be replaced.
If provided with None, will return None.
.. code-block:: text
:caption: Example
>>> pd = ParamDocs(p1="doc1", p2="doc2
doc2 seco... | format_docstring | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def format_docstring(param_docs):
"""
Returns a decorator that replaces param doc placeholders (e.g. '{{ param_name }}') in the
docstring of the decorated function.
Args:
param_docs: A `ParamDocs` instance or `dict`.
Returns:
A decorator to apply the formatting.
.. code-block:... |
Returns a decorator that replaces param doc placeholders (e.g. '{{ param_name }}') in the
docstring of the decorated function.
Args:
param_docs: A `ParamDocs` instance or `dict`.
Returns:
A decorator to apply the formatting.
.. code-block:: text
:caption: Example
... | format_docstring | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def get_module_min_and_max_supported_ranges(flavor_name):
"""
Extracts the minimum and maximum supported package versions from the provided module name.
The version information is provided via the yaml-to-python-script generation script in
dev/update_ml_package_versions.py which writes a python file to ... |
Extracts the minimum and maximum supported package versions from the provided module name.
The version information is provided via the yaml-to-python-script generation script in
dev/update_ml_package_versions.py which writes a python file to the importable namespace of
mlflow.ml_package_versions
A... | get_module_min_and_max_supported_ranges | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def docstring_version_compatibility_warning(integration_name):
"""
Generates a docstring that can be applied as a note stating a version compatibility range for
a given flavor and optionally raises a warning if the installed version is outside of the
supported range.
Args:
integration_name:... |
Generates a docstring that can be applied as a note stating a version compatibility range for
a given flavor and optionally raises a warning if the installed version is outside of the
supported range.
Args:
integration_name: The name of the module as stored within ml-package-versions.yml
... | docstring_version_compatibility_warning | python | mlflow/mlflow | mlflow/utils/docstring_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/docstring_utils.py | Apache-2.0 |
def doctor(mask_envs=False):
"""Prints out useful information for debugging issues with MLflow.
Args:
mask_envs: If True, mask the MLflow environment variable values
(e.g. `"MLFLOW_ENV_VAR": "***"`) in the output to prevent leaking sensitive
information.
.. warning::
... | Prints out useful information for debugging issues with MLflow.
Args:
mask_envs: If True, mask the MLflow environment variable values
(e.g. `"MLFLOW_ENV_VAR": "***"`) in the output to prevent leaking sensitive
information.
.. warning::
- This API should only be used fo... | doctor | python | mlflow/mlflow | mlflow/utils/doctor.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/doctor.py | Apache-2.0 |
def __init__(self, python=None, build_dependencies=None, dependencies=None):
"""
Represents environment information for MLflow Models and Projects.
Args:
python: Python version for the environment. If unspecified, defaults to the current
Python version.
b... |
Represents environment information for MLflow Models and Projects.
Args:
python: Python version for the environment. If unspecified, defaults to the current
Python version.
build_dependencies: List of build dependencies for the environment that must
... | __init__ | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _mlflow_conda_env( # noqa: D417
path=None,
additional_conda_deps=None,
additional_pip_deps=None,
additional_conda_channels=None,
install_mlflow=True,
):
"""Creates a Conda environment with the specified package channels and dependencies. If there
are any pip dependencies, including from... | Creates a Conda environment with the specified package channels and dependencies. If there
are any pip dependencies, including from the install_mlflow parameter, then pip will be added to
the conda dependencies. This is done to ensure that the pip inside the conda environment is
used to install the pip depe... | _mlflow_conda_env | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _get_pip_deps(conda_env):
"""
Returns:
The pip dependencies from the conda env.
"""
if conda_env is not None:
for dep in conda_env["dependencies"]:
if _is_pip_deps(dep):
return dep["pip"]
return [] |
Returns:
The pip dependencies from the conda env.
| _get_pip_deps | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _overwrite_pip_deps(conda_env, new_pip_deps):
"""
Overwrites the pip dependencies section in the given conda env dictionary.
{
"name": "env",
"channels": [...],
"dependencies": [
...,
"pip",
{"pip": [...]}, <- Overwrite this
],
}
... |
Overwrites the pip dependencies section in the given conda env dictionary.
{
"name": "env",
"channels": [...],
"dependencies": [
...,
"pip",
{"pip": [...]}, <- Overwrite this
],
}
| _overwrite_pip_deps | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _parse_pip_requirements(pip_requirements):
"""Parses an iterable of pip requirement strings or a pip requirements file.
Args:
pip_requirements: Either an iterable of pip requirement strings
(e.g. ``["scikit-learn", "-r requirements.txt"]``) or the string path to a pip
requir... | Parses an iterable of pip requirement strings or a pip requirements file.
Args:
pip_requirements: Either an iterable of pip requirement strings
(e.g. ``["scikit-learn", "-r requirements.txt"]``) or the string path to a pip
requirements file on the local filesystem (e.g. ``"requireme... | _parse_pip_requirements | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def infer_pip_requirements(model_uri, flavor, fallback=None, timeout=None, 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... | 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.
fallback: If provided, an unexpected error during the inference ... | infer_pip_requirements | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _get_uv_options_for_databricks() -> tuple[list[str], dict[str, str]]:
"""
Retrieves the predefined secrets to configure `pip` for Databricks, and converts them into
command-line arguments and environment variables for `uv`.
References:
- https://docs.databricks.com/aws/en/compute/serverless/dep... |
Retrieves the predefined secrets to configure `pip` for Databricks, and converts them into
command-line arguments and environment variables for `uv`.
References:
- https://docs.databricks.com/aws/en/compute/serverless/dependencies#predefined-secret-scope-name
- https://docs.astral.sh/uv/configurat... | _get_uv_options_for_databricks | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def get_secret(key: str) -> Optional[str]:
"""
Retrieves a secret from the Databricks secrets scope.
"""
try:
return dbutils.secrets.get(scope="databricks-package-management", key=key)
except Exception as e:
_logger.debug(f"Failed to fetch secret '{key}': ... |
Retrieves a secret from the Databricks secrets scope.
| get_secret | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _lock_requirements(
requirements: list[str], constraints: Optional[list[str]] = None
) -> Optional[list[str]]:
"""
Locks the given requirements using `uv`. Returns the locked requirements when the locking is
performed successfully, otherwise returns None.
"""
if not MLFLOW_LOCK_MODEL_DEPENDE... |
Locks the given requirements using `uv`. Returns the locked requirements when the locking is
performed successfully, otherwise returns None.
| _lock_requirements | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements):
"""
Validates that only one or none of `conda_env`, `pip_requirements`, and
`extra_pip_requirements` is specified.
"""
args = [
conda_env,
pip_requirements,
extra_pip_requirements,
]
spe... |
Validates that only one or none of `conda_env`, `pip_requirements`, and
`extra_pip_requirements` is specified.
| _validate_env_arguments | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _is_mlflow_requirement(requirement_string):
"""
Returns True if `requirement_string` represents a requirement for mlflow (e.g. 'mlflow==1.2.3').
"""
# "/opt/mlflow" is the path where we mount the mlflow source code in the Docker container
# when running tests.
if _MLFLOW_TESTING.get() and re... |
Returns True if `requirement_string` represents a requirement for mlflow (e.g. 'mlflow==1.2.3').
| _is_mlflow_requirement | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _generate_mlflow_version_pinning() -> str:
"""Returns a pinned requirement for the current MLflow version (e.g., "mlflow==3.2.1").
Returns:
A pinned requirement for the current MLflow version.
"""
if _MLFLOW_TESTING.get():
# The local PyPI server should be running. It serves a whee... | Returns a pinned requirement for the current MLflow version (e.g., "mlflow==3.2.1").
Returns:
A pinned requirement for the current MLflow version.
| _generate_mlflow_version_pinning | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _process_pip_requirements(
default_pip_requirements, pip_requirements=None, extra_pip_requirements=None
):
"""
Processes `pip_requirements` and `extra_pip_requirements` passed to `mlflow.*.save_model` or
`mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints).
... |
Processes `pip_requirements` and `extra_pip_requirements` passed to `mlflow.*.save_model` or
`mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints).
| _process_pip_requirements | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _deduplicate_requirements(requirements):
"""
De-duplicates a list of pip package requirements, handling complex scenarios such as merging
extras and combining version constraints.
This function processes a list of pip package requirements and de-duplicates them. It handles
standard PyPI package... |
De-duplicates a list of pip package requirements, handling complex scenarios such as merging
extras and combining version constraints.
This function processes a list of pip package requirements and de-duplicates them. It handles
standard PyPI packages and non-standard requirements (like URLs or local ... | _deduplicate_requirements | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _validate_version_constraints(requirements):
"""
Validates the version constraints of given Python package requirements using pip's resolver with
the `--dry-run` option enabled that performs validation only (will not install packages).
This function writes the requirements to a temporary file and t... |
Validates the version constraints of given Python package requirements using pip's resolver with
the `--dry-run` option enabled that performs validation only (will not install packages).
This function writes the requirements to a temporary file and then attempts to resolve
them using pip's `--dry-run`... | _validate_version_constraints | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _process_conda_env(conda_env):
"""
Processes `conda_env` passed to `mlflow.*.save_model` or `mlflow.*.log_model`, and returns
a tuple of (conda_env, pip_requirements, pip_constraints).
"""
if isinstance(conda_env, str):
with open(conda_env) as f:
conda_env = yaml.safe_load(f)... |
Processes `conda_env` passed to `mlflow.*.save_model` or `mlflow.*.log_model`, and returns
a tuple of (conda_env, pip_requirements, pip_constraints).
| _process_conda_env | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _get_pip_install_mlflow():
"""
Returns a command to pip-install mlflow. If the MLFLOW_HOME environment variable exists,
returns "pip install -e {MLFLOW_HOME} 1>&2", otherwise
"pip install mlflow=={mlflow.__version__} 1>&2".
"""
mlflow_home = os.getenv("MLFLOW_HOME")
if mlflow_home: # de... |
Returns a command to pip-install mlflow. If the MLFLOW_HOME environment variable exists,
returns "pip install -e {MLFLOW_HOME} 1>&2", otherwise
"pip install mlflow=={mlflow.__version__} 1>&2".
| _get_pip_install_mlflow | python | mlflow/mlflow | mlflow/utils/environment.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/environment.py | Apache-2.0 |
def _tar(root_path: Path, tar_path: Path) -> tarfile.TarFile:
"""
Package all files under root_path into a tar at tar_path, excluding __pycache__, *.pyc, and
wheels_info.json.
"""
def exclude(tarinfo: tarfile.TarInfo):
name = tarinfo.name
base = Path(name).name
if "__pycache... |
Package all files under root_path into a tar at tar_path, excluding __pycache__, *.pyc, and
wheels_info.json.
| _tar | python | mlflow/mlflow | mlflow/utils/env_pack.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/env_pack.py | Apache-2.0 |
def pack_env_for_databricks_model_serving(
model_uri: str,
*,
enforce_pip_requirements: bool = False,
) -> Generator[str, None, None]:
"""
Generate Databricks artifacts for fast deployment.
Args:
model_uri: The URI of the model to package.
enforce_pip_requirements: Whether to en... |
Generate Databricks artifacts for fast deployment.
Args:
model_uri: The URI of the model to package.
enforce_pip_requirements: Whether to enforce pip requirements installation.
Yields:
str: The path to the local artifacts directory containing the model artifacts and
en... | pack_env_for_databricks_model_serving | python | mlflow/mlflow | mlflow/utils/env_pack.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/env_pack.py | Apache-2.0 |
def list_all(root, filter_func=lambda x: True, full_path=False):
"""List all entities directly under 'dir_name' that satisfy 'filter_func'
Args:
root: Name of directory to start search.
filter_func: function or lambda that takes path.
full_path: If True will return results as full path ... | List all entities directly under 'dir_name' that satisfy 'filter_func'
Args:
root: Name of directory to start search.
filter_func: function or lambda that takes path.
full_path: If True will return results as full path including `root`.
Returns:
list of all files or directories... | list_all | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def find(root, name, full_path=False):
"""Search for a file in a root directory. Equivalent to:
``find $root -name "$name" -depth 1``
Args:
root: Name of root directory for find.
name: Name of file or directory to find directly under root directory.
full_path: If True will return ... | Search for a file in a root directory. Equivalent to:
``find $root -name "$name" -depth 1``
Args:
root: Name of root directory for find.
name: Name of file or directory to find directly under root directory.
full_path: If True will return results as full path including `root`.
Re... | find | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def mkdir(root, name=None):
"""Make directory with name "root/name", or just "root" if name is None.
Args:
root: Name of parent directory.
name: Optional name of leaf directory.
Returns:
Path to created directory.
"""
target = os.path.join(root, name) if name is not None el... | Make directory with name "root/name", or just "root" if name is None.
Args:
root: Name of parent directory.
name: Optional name of leaf directory.
Returns:
Path to created directory.
| mkdir | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def make_containing_dirs(path):
"""
Create the base directory for a given file path if it does not exist; also creates parent
directories.
"""
dir_name = os.path.dirname(path)
if not os.path.exists(dir_name):
os.makedirs(dir_name) |
Create the base directory for a given file path if it does not exist; also creates parent
directories.
| make_containing_dirs | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def read_parquet_as_pandas_df(data_parquet_path: str):
"""Deserialize and load the specified parquet file as a Pandas DataFrame.
Args:
data_parquet_path: String, path object (implementing os.PathLike[str]),
or file-like object implementing a binary read() function. The string
co... | Deserialize and load the specified parquet file as a Pandas DataFrame.
Args:
data_parquet_path: String, path object (implementing os.PathLike[str]),
or file-like object implementing a binary read() function. The string
could be a URL. Valid URL schemes include http, ftp, s3, gs, and... | read_parquet_as_pandas_df | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def read_file_lines(parent_path, file_name):
"""Return the contents of the file as an array where each element is a separate line.
Args:
parent_path: Full path to the directory that contains the file.
file_name: Leaf file name.
Returns:
All lines in the file as an array.
"""
... | Return the contents of the file as an array where each element is a separate line.
Args:
parent_path: Full path to the directory that contains the file.
file_name: Leaf file name.
Returns:
All lines in the file as an array.
| read_file_lines | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def read_file(parent_path, file_name):
"""Return the contents of the file.
Args:
parent_path: Full path to the directory that contains the file.
file_name: Leaf file name.
Returns:
The contents of the file.
"""
file_path = os.path.join(parent_path, file_name)
with code... | Return the contents of the file.
Args:
parent_path: Full path to the directory that contains the file.
file_name: Leaf file name.
Returns:
The contents of the file.
| read_file | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_file_info(path, rel_path):
"""Returns file meta data : location, size, ... etc
Args:
path: Path to artifact.
rel_path: Relative path.
Returns:
`FileInfo` object
"""
if is_directory(path):
return FileInfo(rel_path, True, None)
else:
return FileInf... | Returns file meta data : location, size, ... etc
Args:
path: Path to artifact.
rel_path: Relative path.
Returns:
`FileInfo` object
| get_file_info | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_relative_path(root_path, target_path):
"""Remove root path common prefix and return part of `path` relative to `root_path`.
Args:
root_path: Root path.
target_path: Desired path for common prefix removal.
Returns:
Path relative to root_path.
"""
if len(root_path) > ... | Remove root path common prefix and return part of `path` relative to `root_path`.
Args:
root_path: Root path.
target_path: Desired path for common prefix removal.
Returns:
Path relative to root_path.
| get_relative_path | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def _copy_project(src_path, dst_path=""):
"""Internal function used to copy MLflow project during development.
Copies the content of the whole directory tree except patterns defined in .dockerignore.
The MLflow is assumed to be accessible as a local directory in this case.
Args:
src_path: Path... | Internal function used to copy MLflow project during development.
Copies the content of the whole directory tree except patterns defined in .dockerignore.
The MLflow is assumed to be accessible as a local directory in this case.
Args:
src_path: Path to the original MLflow project
dst_path:... | _copy_project | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def _copy_file_or_tree(src, dst, dst_dir=None):
"""
Returns:
The path to the copied artifacts, relative to `dst`.
"""
dst_subpath = os.path.basename(os.path.abspath(src))
if dst_dir is not None:
dst_subpath = os.path.join(dst_dir, dst_subpath)
dst_path = os.path.join(dst, dst_sub... |
Returns:
The path to the copied artifacts, relative to `dst`.
| _copy_file_or_tree | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def _get_local_project_dir_size(project_path):
"""Internal function for reporting the size of a local project directory before copying to
destination for cli logging reporting to stdout.
Args:
project_path: local path of the project directory
Returns:
directory file sizes in KB, rounde... | Internal function for reporting the size of a local project directory before copying to
destination for cli logging reporting to stdout.
Args:
project_path: local path of the project directory
Returns:
directory file sizes in KB, rounded to single decimal point for legibility
| _get_local_project_dir_size | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def path_to_local_sqlite_uri(path):
"""
Convert local filesystem path to sqlite uri.
"""
path = posixpath.abspath(pathname2url(os.path.abspath(path)))
prefix = "sqlite://" if sys.platform == "win32" else "sqlite:///"
return prefix + path |
Convert local filesystem path to sqlite uri.
| path_to_local_sqlite_uri | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def local_file_uri_to_path(uri):
"""
Convert URI to local filesystem path.
No-op if the uri does not have the expected scheme.
"""
path = uri
if uri.startswith("file:"):
parsed_path = urllib.parse.urlparse(uri)
path = parsed_path.path
# Fix for retaining server name in UN... |
Convert URI to local filesystem path.
No-op if the uri does not have the expected scheme.
| local_file_uri_to_path | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_local_path_or_none(path_or_uri):
"""Check if the argument is a local path (no scheme or file:///) and return local path if true,
None otherwise.
"""
parsed_uri = urllib.parse.urlparse(path_or_uri)
if len(parsed_uri.scheme) == 0 or parsed_uri.scheme == "file" and len(parsed_uri.netloc) == 0:
... | Check if the argument is a local path (no scheme or file:///) and return local path if true,
None otherwise.
| get_local_path_or_none | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def yield_file_in_chunks(file, chunk_size=100000000):
"""
Generator to chunk-ify the inputted file based on the chunk-size.
"""
with open(file, "rb") as f:
while True:
chunk = f.read(chunk_size)
if chunk:
yield chunk
else:
break |
Generator to chunk-ify the inputted file based on the chunk-size.
| yield_file_in_chunks | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def download_file_using_http_uri(http_uri, download_path, chunk_size=100000000, headers=None):
"""
Downloads a file specified using the `http_uri` to a local `download_path`. This function
uses a `chunk_size` to ensure an OOM error is not raised a large file is downloaded.
Note : This function is meant... |
Downloads a file specified using the `http_uri` to a local `download_path`. This function
uses a `chunk_size` to ensure an OOM error is not raised a large file is downloaded.
Note : This function is meant to download files using presigned urls from various cloud
providers.
| download_file_using_http_uri | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def parallelized_download_file_using_http_uri(
thread_pool_executor,
http_uri,
download_path,
remote_file_path,
file_size,
uri_type,
chunk_size,
env,
headers=None,
):
"""
Downloads a file specified using the `http_uri` to a local `download_path`. This function
sends multi... |
Downloads a file specified using the `http_uri` to a local `download_path`. This function
sends multiple requests in parallel each specifying its own desired byte range as a header,
then reconstructs the file from the downloaded chunks. This allows for downloads of large files
without OOM risk.
No... | parallelized_download_file_using_http_uri | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def _handle_readonly_on_windows(func, path, exc_info):
"""
This function should not be called directly but should be passed to `onerror` of
`shutil.rmtree` in order to reattempt the removal of a read-only file after making
it writable on Windows.
References:
- https://bugs.python.org/issue19643... |
This function should not be called directly but should be passed to `onerror` of
`shutil.rmtree` in order to reattempt the removal of a read-only file after making
it writable on Windows.
References:
- https://bugs.python.org/issue19643
- https://bugs.python.org/issue43657
| _handle_readonly_on_windows | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_or_create_tmp_dir():
"""
Get or create a temporary directory which will be removed once python process exit.
"""
from mlflow.utils.databricks_utils import get_repl_id, is_in_databricks_runtime
if is_in_databricks_runtime() and get_repl_id() is not None:
# Note: For python process at... |
Get or create a temporary directory which will be removed once python process exit.
| get_or_create_tmp_dir | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_or_create_nfs_tmp_dir():
"""
Get or create a temporary NFS directory which will be removed once python process exit.
"""
from mlflow.utils.databricks_utils import get_repl_id, is_in_databricks_runtime
from mlflow.utils.nfs_on_spark import get_nfs_cache_root_dir
nfs_root_dir = get_nfs_ca... |
Get or create a temporary NFS directory which will be removed once python process exit.
| get_or_create_nfs_tmp_dir | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def write_spark_dataframe_to_parquet_on_local_disk(spark_df, output_path):
"""Write spark dataframe in parquet format to local disk.
Args:
spark_df: Spark dataframe.
output_path: Path to write the data to.
"""
from mlflow.utils.databricks_utils import is_in_databricks_runtime
if i... | Write spark dataframe in parquet format to local disk.
Args:
spark_df: Spark dataframe.
output_path: Path to write the data to.
| write_spark_dataframe_to_parquet_on_local_disk | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def shutil_copytree_without_file_permissions(src_dir, dst_dir):
"""
Copies the directory src_dir into dst_dir, without preserving filesystem permissions
"""
for dirpath, dirnames, filenames in os.walk(src_dir):
for dirname in dirnames:
relative_dir_path = os.path.relpath(os.path.join... |
Copies the directory src_dir into dst_dir, without preserving filesystem permissions
| shutil_copytree_without_file_permissions | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def read_chunk(path: os.PathLike, size: int, start_byte: int = 0) -> bytes:
"""Read a chunk of bytes from a file.
Args:
path: Path to the file.
size: The size of the chunk.
start_byte: The start byte of the chunk.
Returns:
The chunk of bytes.
"""
with open(path, "r... | Read a chunk of bytes from a file.
Args:
path: Path to the file.
size: The size of the chunk.
start_byte: The start byte of the chunk.
Returns:
The chunk of bytes.
| read_chunk | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def remove_on_error(path: os.PathLike, onerror=None):
"""A context manager that removes a file or directory if an exception is raised during
execution.
Args:
path: Path to the file or directory.
onerror: A callback function that will be called with the captured exception before
... | A context manager that removes a file or directory if an exception is raised during
execution.
Args:
path: Path to the file or directory.
onerror: A callback function that will be called with the captured exception before
the file or directory is removed. For example, you can use th... | remove_on_error | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def chdir(path: str) -> None:
"""Temporarily change the current working directory to the specified path.
Args:
path: The path to use as the temporary working directory.
"""
cwd = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(cwd) | Temporarily change the current working directory to the specified path.
Args:
path: The path to use as the temporary working directory.
| chdir | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_total_file_size(path: Union[str, pathlib.Path]) -> Optional[int]:
"""Return the size of all files under given path, including files in subdirectories.
Args:
path: The absolute path of a local directory.
Returns:
size in bytes.
"""
try:
if isinstance(path, pathlib.P... | Return the size of all files under given path, including files in subdirectories.
Args:
path: The absolute path of a local directory.
Returns:
size in bytes.
| get_total_file_size | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def write_yaml(
root: str,
file_name: str,
data: dict[str, Any],
overwrite: bool = False,
sort_keys: bool = True,
ensure_yaml_extension: bool = True,
) -> None:
"""
NEVER TOUCH THIS FUNCTION. KEPT FOR BACKWARD COMPATIBILITY with
databricks-feature-engineering<=0.10.2
"""
impo... |
NEVER TOUCH THIS FUNCTION. KEPT FOR BACKWARD COMPATIBILITY with
databricks-feature-engineering<=0.10.2
| write_yaml | python | mlflow/mlflow | mlflow/utils/file_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/file_utils.py | Apache-2.0 |
def get_git_repo_url(path: str) -> Optional[str]:
"""
Obtains the url of the git repository associated with the specified path,
returning ``None`` if the path does not correspond to a git repository.
"""
try:
from git import Repo
except ImportError as e:
_logger.warning(
... |
Obtains the url of the git repository associated with the specified path,
returning ``None`` if the path does not correspond to a git repository.
| get_git_repo_url | python | mlflow/mlflow | mlflow/utils/git_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/git_utils.py | Apache-2.0 |
def get_git_branch(path: str) -> Optional[str]:
"""
Obtains the name of the current branch of the git repository associated with the specified
path, returning ``None`` if the path does not correspond to a git repository.
"""
try:
from git import Repo
except ImportError as e:
_log... |
Obtains the name of the current branch of the git repository associated with the specified
path, returning ``None`` if the path does not correspond to a git repository.
| get_git_branch | python | mlflow/mlflow | mlflow/utils/git_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/git_utils.py | Apache-2.0 |
def __init__(self, **kwargs):
"""Constructor.
Parameters
----------
kwargs
Keyword arguments, see the attributes.
"""
self.allow_hit = False
self.store_hit = True
self._update(**kwargs) | Constructor.
Parameters
----------
kwargs
Keyword arguments, see the attributes.
| __init__ | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def __init__(self, destination, name, obj, settings=None):
"""Constructor.
Parameters
----------
destination : object
See the :attr:`~Patch.destination` attribute.
name : str
See the :attr:`~Patch.name` attribute.
obj : object
See the ... | Constructor.
Parameters
----------
destination : object
See the :attr:`~Patch.destination` attribute.
name : str
See the :attr:`~Patch.name` attribute.
obj : object
See the :attr:`~Patch.obj` attribute.
settings : gorilla.Settings
... | __init__ | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def _update(self, **kwargs):
"""Update some attributes.
If a 'settings' attribute is passed as a dict, then it will update the
content of the settings, if any, instead of completely overwriting it.
Parameters
----------
kwargs
Attributes to update.
... | Update some attributes.
If a 'settings' attribute is passed as a dict, then it will update the
content of the settings, if any, instead of completely overwriting it.
Parameters
----------
kwargs
Attributes to update.
Raises
------
ValueError... | _update | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def apply(patch):
"""Apply a patch.
The patch's :attr:`~Patch.obj` attribute is injected into the patch's
:attr:`~Patch.destination` under the patch's :attr:`~Patch.name`.
This is a wrapper around calling
``setattr(patch.destination, patch.name, patch.obj)``.
Parameters
----------
pat... | Apply a patch.
The patch's :attr:`~Patch.obj` attribute is injected into the patch's
:attr:`~Patch.destination` under the patch's :attr:`~Patch.name`.
This is a wrapper around calling
``setattr(patch.destination, patch.name, patch.obj)``.
Parameters
----------
patch : gorilla.Patch
... | apply | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def revert(patch):
"""Revert a patch.
Parameters
----------
patch : gorilla.Patch
Patch.
Note
----
This is only possible if the attribute :attr:`Settings.store_hit` was set
to ``True`` when applying the patch and overriding an existing attribute.
Notice:
This method is ... | Revert a patch.
Parameters
----------
patch : gorilla.Patch
Patch.
Note
----
This is only possible if the attribute :attr:`Settings.store_hit` was set
to ``True`` when applying the patch and overriding an existing attribute.
Notice:
This method is taken from
https://git... | revert | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def patch(destination, name=None, settings=None):
"""Decorator to create a patch.
The object being decorated becomes the :attr:`~Patch.obj` attribute of the
patch.
Parameters
----------
destination : object
Patch destination.
name : str
Name of the attribute at the destinat... | Decorator to create a patch.
The object being decorated becomes the :attr:`~Patch.obj` attribute of the
patch.
Parameters
----------
destination : object
Patch destination.
name : str
Name of the attribute at the destination.
settings : gorilla.Settings
Settings.
... | patch | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def destination(value):
"""Modifier decorator to update a patch's destination.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
... | Modifier decorator to update a patch's destination.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
Patch destination.
... | destination | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def name(value):
"""Modifier decorator to update a patch's name.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
Patch n... | Modifier decorator to update a patch's name.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
Patch name.
Returns
--... | name | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def settings(**kwargs):
"""Modifier decorator to update a patch's settings.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
kwargs
Sett... | Modifier decorator to update a patch's settings.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
kwargs
Settings to update. See :class:`Set... | settings | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def filter(value):
"""Modifier decorator to force the inclusion or exclusion of an attribute.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
v... | Modifier decorator to force the inclusion or exclusion of an attribute.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : bool
``True... | filter | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def find_patches(modules, recursive=True):
"""Find all the patches created through decorators.
Parameters
----------
modules : list of module
Modules and/or packages to search the patches in.
recursive : bool
``True`` to search recursively in subpackages.
Returns
-------
... | Find all the patches created through decorators.
Parameters
----------
modules : list of module
Modules and/or packages to search the patches in.
recursive : bool
``True`` to search recursively in subpackages.
Returns
-------
list of gorilla.Patch
Patches found.
... | find_patches | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def get_original_attribute(obj, name, bypass_descriptor_protocol=False):
"""Retrieve an overridden attribute that has been stored.
Parameters
----------
obj : object
Object to search the attribute in.
name : str
Name of the attribute.
bypass_descriptor_protocol: boolean
... | Retrieve an overridden attribute that has been stored.
Parameters
----------
obj : object
Object to search the attribute in.
name : str
Name of the attribute.
bypass_descriptor_protocol: boolean
bypassing descriptor protocol if true. When storing original method during patch... | get_original_attribute | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def get_decorator_data(obj, set_default=False):
"""Retrieve any decorator data from an object.
Parameters
----------
obj : object
Object.
set_default : bool
If no data is found, a default one is set on the object and returned,
otherwise ``None`` is returned.
Returns
... | Retrieve any decorator data from an object.
Parameters
----------
obj : object
Object.
set_default : bool
If no data is found, a default one is set on the object and returned,
otherwise ``None`` is returned.
Returns
-------
gorilla.DecoratorData
The decorato... | get_decorator_data | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def _get_base(obj):
"""Unwrap decorators to retrieve the base object.
Parameters
----------
obj : object
Object.
Returns
-------
object
The base object found or the input object otherwise.
"""
if hasattr(obj, "__func__"):
obj = obj.__func__
elif isinstan... | Unwrap decorators to retrieve the base object.
Parameters
----------
obj : object
Object.
Returns
-------
object
The base object found or the input object otherwise.
| _get_base | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def _get_members(obj, traverse_bases=True, filter=default_filter, recursive=True):
"""Retrieve the member attributes of a module or a class.
The descriptor protocol is bypassed.
Parameters
----------
obj : module or class
Object.
traverse_bases : bool
If the object is a class, ... | Retrieve the member attributes of a module or a class.
The descriptor protocol is bypassed.
Parameters
----------
obj : module or class
Object.
traverse_bases : bool
If the object is a class, the base classes are also traversed.
filter : function
Attributes for which th... | _get_members | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def _module_iterator(root, recursive=True):
"""Iterate over modules.
Parameters
----------
root : module
Root module or package to iterate from.
recursive : bool
``True`` to iterate within subpackages.
Yields
------
module
The modules found.
"""
yield ro... | Iterate over modules.
Parameters
----------
root : module
Root module or package to iterate from.
recursive : bool
``True`` to iterate within subpackages.
Yields
------
module
The modules found.
| _module_iterator | python | mlflow/mlflow | mlflow/utils/gorilla.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/gorilla.py | Apache-2.0 |
def suppress_logs(module: str, filter_regex: re.Pattern):
"""
Context manager that suppresses log messages from the specified module that match the specified
regular expression. This is useful for suppressing expected log messages from third-party
libraries that are not relevant to the current test.
... |
Context manager that suppresses log messages from the specified module that match the specified
regular expression. This is useful for suppressing expected log messages from third-party
libraries that are not relevant to the current test.
| suppress_logs | python | mlflow/mlflow | mlflow/utils/logging_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/logging_utils.py | Apache-2.0 |
def _get_flavor_configuration(model_path, flavor_name):
"""Obtains the configuration for the specified flavor from the specified
MLflow model path. If the model does not contain the specified flavor,
an exception will be thrown.
Args:
model_path: The path to the root directory of the MLflow mod... | Obtains the configuration for the specified flavor from the specified
MLflow model path. If the model does not contain the specified flavor,
an exception will be thrown.
Args:
model_path: The path to the root directory of the MLflow model for which to load
the specified flavor configura... | _get_flavor_configuration | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _get_flavor_configuration_from_uri(model_uri, flavor_name, logger):
"""Obtains the configuration for the specified flavor from the specified
MLflow model uri. If the model does not contain the specified flavor,
an exception will be thrown.
Args:
model_uri: The path to the root directory of ... | Obtains the configuration for the specified flavor from the specified
MLflow model uri. If the model does not contain the specified flavor,
an exception will be thrown.
Args:
model_uri: The path to the root directory of the MLflow model for which to load
the specified flavor configurati... | _get_flavor_configuration_from_uri | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _validate_and_copy_code_paths(code_paths, path, default_subpath="code"):
"""Validates that a code path is a valid list and copies the code paths to a directory. This
can later be used to log custom code as an artifact.
Args:
code_paths: A list of files or directories containing code that should... | Validates that a code path is a valid list and copies the code paths to a directory. This
can later be used to log custom code as an artifact.
Args:
code_paths: A list of files or directories containing code that should be logged
as artifacts.
path: The local model path.
def... | _validate_and_copy_code_paths | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _validate_and_copy_file_to_directory(file_path: str, dir_path: str, name: str):
"""Copies the file at file_path to the directory at dir_path.
Args:
file_path: A file that should be logged as an artifact.
dir_path: The path of the directory to save the file to.
name: The name for the... | Copies the file at file_path to the directory at dir_path.
Args:
file_path: A file that should be logged as an artifact.
dir_path: The path of the directory to save the file to.
name: The name for the kind of file being copied.
| _validate_and_copy_file_to_directory | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _add_code_from_conf_to_system_path(local_path, conf, code_key=FLAVOR_CONFIG_CODE):
"""Checks if any code_paths were logged with the model in the flavor conf and prepends
the directory to the system path.
Args:
local_path: The local path containing model artifacts.
conf: The flavor-speci... | Checks if any code_paths were logged with the model in the flavor conf and prepends
the directory to the system path.
Args:
local_path: The local path containing model artifacts.
conf: The flavor-specific conf that should contain the FLAVOR_CONFIG_CODE
key, which specifies the direc... | _add_code_from_conf_to_system_path | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _validate_onnx_session_options(onnx_session_options):
"""Validates that the specified onnx_session_options dict is valid.
Args:
onnx_session_options: The onnx_session_options dict to validate.
"""
import onnxruntime as ort
if onnx_session_options is not None:
if not isinstance(... | Validates that the specified onnx_session_options dict is valid.
Args:
onnx_session_options: The onnx_session_options dict to validate.
| _validate_onnx_session_options | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _get_overridden_pyfunc_model_config(
pyfunc_config: dict[str, Any], load_config: dict[str, Any], logger
) -> dict[str, Any]:
"""
Updates the inference configuration according to the model's configuration and the overrides.
Only arguments already present in the inference configuration can be updated.... |
Updates the inference configuration according to the model's configuration and the overrides.
Only arguments already present in the inference configuration can be updated. The environment
variable ``MLFLOW_PYFUNC_INFERENCE_CONFIG`` can also be used to provide additional inference
configuration.
| _get_overridden_pyfunc_model_config | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _validate_pyfunc_model_config(model_config):
"""
Validates the values passes in the model_config section. There are no typing
restrictions but we require them being JSON-serializable.
"""
if not model_config:
return
if isinstance(model_config, Path):
_validate_and_get_model... |
Validates the values passes in the model_config section. There are no typing
restrictions but we require them being JSON-serializable.
| _validate_pyfunc_model_config | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def env_var_tracker():
"""
Context manager for temporarily tracking environment variables accessed.
It tracks environment variables accessed during the context manager's lifetime.
"""
from mlflow.environment_variables import MLFLOW_RECORD_ENV_VARS_IN_MODEL_LOGGING
tracked_env_names = set()
... |
Context manager for temporarily tracking environment variables accessed.
It tracks environment variables accessed during the context manager's lifetime.
| env_var_tracker | python | mlflow/mlflow | mlflow/utils/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/model_utils.py | Apache-2.0 |
def _generate_unique_integer_id():
"""Utility function for generating a random fixed-length integer
Args:
id_length: The target length of the string representation of the integer without
leading zeros
Returns:
a fixed-width integer
"""
random_int = uuid.uuid4().int
... | Utility function for generating a random fixed-length integer
Args:
id_length: The target length of the string representation of the integer without
leading zeros
Returns:
a fixed-width integer
| _generate_unique_integer_id | python | mlflow/mlflow | mlflow/utils/name_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/name_utils.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.