Repository navigation
Expand file tree
/
Copy pathmodel_helper.py
More file actions
80 lines (69 loc) · 2.45 KB
/
Copy pathmodel_helper.py
File metadata and controls
80 lines (69 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
model_helper.py
"""
from azureml.core import Run
from azureml.core import Workspace
from azureml.core.model import Model as AMLModel
def get_current_workspace() -> Workspace:
"""
Retrieves and returns the latest model from the workspace
by its name and tag. Will not work when ran locally.
Parameters:
None
Return:
The current workspace.
"""
run = Run.get_context(allow_offline=False)
experiment = run.experiment
return experiment.workspace
def get_model_by_tag(
model_name: str,
tag_name: str,
tag_value: str,
aml_workspace: Workspace = None
) -> AMLModel:
"""
Retrieves and returns the latest model from the workspace
by its name and tag.
Parameters:
aml_workspace (Workspace): aml.core Workspace that the model lives.
model_name (str): name of the model we are looking for
tag (str): the tag value the model was registered under.
Return:
A single aml model from the workspace that matches the name and tag.
"""
try:
# Validate params. cannot be None.
if model_name is None:
raise ValueError("model_name[:str] is required")
if tag_name is None:
raise ValueError("tag_name[:str] is required")
if tag_value is None:
raise ValueError("tag[:str] is required")
if aml_workspace is None:
aml_workspace = get_current_workspace()
# get model by tag.
model_list = AMLModel.list(
aml_workspace, name=model_name,
tags=[[tag_name, tag_value]], latest=True
)
# latest should only return 1 model, but if it does,
# then maybe sdk or source code changed.
should_not_happen = ("Found more than one model "
"for the latest with {{tag_name: {tag_name},"
"tag_value: {tag_value}. "
"Models found: {model_list}}}")\
.format(tag_name=tag_name, tag_value=tag_value,
model_list=model_list)
no_model_found = ("No Model found with {{tag_name: {tag_name} ,"
"tag_value: {tag_value}.}}")\
.format(tag_name=tag_name, tag_value=tag_value)
if len(model_list) > 1:
raise ValueError(should_not_happen)
if len(model_list) == 1:
return model_list[0]
else:
print(no_model_found)
return None
except Exception:
raise