Skip to content

Commit 34bc01e

Browse files
authored
Refactor usage of pkg_resources (#1338)
1 parent 424a65d commit 34bc01e

File tree

4 files changed

+52
-29
lines changed

4 files changed

+52
-29
lines changed

ads/common/model_artifact.py

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -971,10 +971,11 @@ def install_requirements(self, conflict_strategy=ConflictStrategy.IGNORE):
971971
IGNORE: Use the installed version in case of a conflict.
972972
UPDATE: Force update dependency to the version required by model artifact in case of conflict.
973973
"""
974-
import pkg_resources
974+
from importlib.metadata import PackageNotFoundError
975+
from importlib.metadata import version as get_version
975976

976-
importlib.reload(pkg_resources)
977-
from pkg_resources import DistributionNotFound, VersionConflict
977+
from packaging.markers import default_environment
978+
from packaging.requirements import Requirement
978979

979980
if self.version.split(".")[0] not in ["0", "1"] and os.path.exists(
980981
Path(os.path.join(self.artifact_dir), "requirements.txt")
@@ -1001,19 +1002,43 @@ def install_requirements(self, conflict_strategy=ConflictStrategy.IGNORE):
10011002
)
10021003

10031004
version_conflicts = {}
1005+
env = default_environment()
10041006
for requirement in requirements:
1007+
req_line = requirement.strip()
1008+
if not req_line or req_line.startswith("#"):
1009+
continue
1010+
# Skip include or index options lines
1011+
if req_line.startswith(("-", "--")):
1012+
continue
10051013
try:
1006-
pkg_resources.require(requirement)
1007-
except VersionConflict as vc:
1014+
req = Requirement(req_line)
1015+
except Exception:
1016+
# If the requirement line cannot be parsed, attempt to install it as-is.
1017+
pip_install(req_line)
1018+
continue
1019+
1020+
# Evaluate environment markers, if any
1021+
if req.marker and not req.marker.evaluate(environment=env):
1022+
continue
1023+
1024+
package_name = req.name
1025+
spec = req.specifier # SpecifierSet
1026+
1027+
try:
1028+
installed_version = get_version(package_name)
1029+
except PackageNotFoundError:
1030+
# Not installed; install the requirement as written
1031+
pip_install(req_line)
1032+
continue
1033+
1034+
if spec and installed_version not in spec:
10081035
if conflict_strategy == ConflictStrategy.UPDATE:
1009-
pip_install("%s%s" % (vc.req.name, vc.req.specifier), "-U")
1036+
pip_install(f"{package_name}{spec}", "-U")
10101037
elif conflict_strategy == ConflictStrategy.IGNORE:
1011-
version_conflicts[
1012-
"%s==%s" % (vc.dist.key, vc.dist.parsed_version)
1013-
] = "%s%s" % (vc.req.name, vc.req.specifier)
1014-
except DistributionNotFound:
1015-
pip_install(requirement)
1016-
# distributions_not_found.add('%s%s' % (dnf.req.name, dnf.req.specifier))
1038+
version_conflicts[f"{package_name}=={installed_version}"] = (
1039+
f"{package_name}{spec}"
1040+
)
1041+
10171042
if len(version_conflicts) > 0:
10181043
print(
10191044
"\033[93m"

ads/common/model_export_util.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,8 @@ def prepare_generic_model(
226226
max_col_num = kwargs.get("max_col_num", utils.DATA_SCHEMA_MAX_COL_NUM)
227227
artifact_type_generic = progress is not None
228228

229-
from pkg_resources import DistributionNotFound, get_distribution
229+
from importlib.metadata import PackageNotFoundError
230+
from importlib.metadata import version as get_version
230231

231232
from ads.common.model import ADSModel
232233

@@ -261,26 +262,22 @@ def prepare_generic_model(
261262
# before we request versions we want to check if fdk installed by user
262263
# and provide support in error message, if not installed
263264
try:
264-
get_distribution("fdk")
265-
except Exception as e:
266-
if isinstance(e, DistributionNotFound):
267-
error_message = (
268-
"fdk library not installed in current environment, it is required "
269-
"for deployment with fn. Install fdk with 'pip install fdk'."
270-
)
271-
logger.error(str(error_message))
272-
raise
265+
get_version("fdk")
266+
except PackageNotFoundError:
267+
error_message = (
268+
"fdk library not installed in current environment, it is required "
269+
"for deployment with fn. Install fdk with 'pip install fdk'."
270+
)
271+
logger.error(str(error_message))
272+
raise
273273
else:
274274
required_fn_libs = get_function_config()["requires"]["functions"]
275-
[
276-
model_libs.update({lib: get_distribution(lib).version})
277-
for lib in required_fn_libs
278-
]
275+
[model_libs.update({lib: get_version(lib)}) for lib in required_fn_libs]
279276
required_model_libs = get_function_config()["requires"][
280277
kwargs.get("serializer", "default")
281278
]
282279
[
283-
model_libs.update({lib: get_distribution(lib).version})
280+
model_libs.update({lib: get_version(lib)})
284281
for lib in required_model_libs
285282
]
286283
utils.generate_requirement_file(

ads/common/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,7 @@ def extract_lib_dependencies_from_model(model) -> dict:
936936
-------
937937
Dict: A dictionary of library dependencies.
938938
"""
939-
from pkg_resources import get_distribution
939+
from importlib.metadata import version as pkg_version
940940

941941
module_versions = {}
942942
modules_to_include = set(
@@ -948,7 +948,7 @@ def extract_lib_dependencies_from_model(model) -> dict:
948948
if mod not in module_ignore:
949949
try:
950950
mod_name = lib_translator.get(mod, mod)
951-
module_versions[mod_name] = get_distribution(mod_name).version
951+
module_versions[mod_name] = pkg_version(mod_name)
952952
except:
953953
pass
954954
return module_versions

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ dependencies = [
8282
"pydantic>=2.6.3",
8383
"tenacity",
8484
"httpx",
85+
"packaging>=21.0",
8586
]
8687

8788
[project.optional-dependencies]

0 commit comments

Comments
 (0)