Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/multi model artifact handler #869

Merged
Merged
Changes from 2 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
6d9fa4a
Initial commit
YashPandit4u May 27, 2024
6a930f1
rename in main module file
YashPandit4u May 27, 2024
5f3b316
Logger used for prints, error handling improved, one extra file creat…
YashPandit4u Jun 1, 2024
802e438
Merge branch 'oracle:main' into feature/multi-model-artifact-handler
YashPandit4u Jun 1, 2024
35e8464
Reformatted using black.
YashPandit4u Jun 1, 2024
e625107
Merge branch 'feature/multi-model-artifact-handler' of https://github…
YashPandit4u Jun 1, 2024
74a235e
Separate logger used.
YashPandit4u Jun 1, 2024
848972e
Added python docs for all methods.
YashPandit4u Jun 1, 2024
d35b917
Added class DataScienceModelCollection that extends from DataScienceM…
YashPandit4u Jun 5, 2024
3ac5338
removed old model description class
YashPandit4u Jun 5, 2024
822c7e8
formatted using black
YashPandit4u Jun 5, 2024
3d4d950
black formatter used and one return type added.
YashPandit4u Jun 5, 2024
d4ef023
Added add_artifact and remove_artifact method in main DataScienceMode…
YashPandit4u Jun 11, 2024
c40ea8b
Removed new added class.
YashPandit4u Jun 11, 2024
d0309f4
Added uri based approach
YashPandit4u Jun 13, 2024
19ec921
Added unit tests.
YashPandit4u Jun 13, 2024
9089028
Changed the pydocs according to ads specifications
YashPandit4u Jun 13, 2024
464cb37
Merge branch 'main' into feature/multi-model-artifact-handler
YashPandit4u Jun 13, 2024
49be8f8
replaces regex with normal splitting for uri
YashPandit4u Jun 13, 2024
a2894a5
Merge branch 'feature/multi-model-artifact-handler' of https://github…
YashPandit4u Jun 13, 2024
5d327cd
removed default_signer
YashPandit4u Jun 13, 2024
b7e7d74
Used ObjectStorageDetails.from_path(uri) for url decoding.
YashPandit4u Jun 13, 2024
4418bf8
namespace, bucket, prefix way added again.
YashPandit4u Jun 14, 2024
e2e7099
Merge branch 'main' into feature/multi-model-artifact-handler
YashPandit4u Jun 14, 2024
4cc8823
Given options for both uri and (namespace, bucket) in add_artifact, r…
YashPandit4u Jun 15, 2024
7f3cc7f
Updated python docs
YashPandit4u Jun 15, 2024
32f4826
Ran black formatter.
YashPandit4u Jun 15, 2024
9f69e35
Ran black formatter of UTs.
YashPandit4u Jun 15, 2024
ad0ce2e
Added uri UTs.
YashPandit4u Jun 15, 2024
eec2b4d
Prefix null check added.
YashPandit4u Jun 15, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions ads/model/model_description.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import json
import ads.common
import oci
import pytz
import datetime
import os
from oci.data_science.models import Metadata
import ads

class ModelDescription:

region = ''
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved

empty_json = {
"version": "1.0",
"type": "modelOSSReferenceDescription",
"models": []
}

def auth(self):
authData = ads.common.auth.default_signer()
signer = authData['signer']
self.region = authData['config']['region']

# data science client
self.data_science_client = oci.data_science.DataScienceClient({'region': self.region}, signer=signer)
# oss client
self.object_storage_client = oci.object_storage.ObjectStorageClient({'region': self.region}, signer = signer)

def __init__(self, model_ocid=None):

self.auth()

if model_ocid == None:
# if no model given then start from scratch
self.modelDescriptionJson = self.empty_json
else:
# if model given then get that as the starting reference point
print("Getting model details from backend")
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
destination_file_path = "downloaded_artifact.json"
get_model_artifact_content_response = self.data_science_client.get_model_artifact_content(
model_id=model_ocid,
)
try:
with open(destination_file_path, "wb") as f:
f.write(get_model_artifact_content_response.data.content)
with open(destination_file_path, 'r') as f:
self.modelDescriptionJson = json.load(f)
except FileNotFoundError:
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
print(f"File '{destination_file_path}' not found.")
except IOError as e:
print(f"Error reading or writing to file: {e}")
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

def add(self, namespace, bucket, prefix=None, files=None):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

recommend using type hinting for all the functions, for example:
def add(self, namespace: str, bucket: str, ... ): -> None

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added type hints.

# Remove if the model already exists
self.remove(namespace, bucket, prefix)

def checkIfFileExists(fileName):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we reuse is_path_exists from ads.common.utils instead?

isExists = False
try:
headResponse = self.object_storage_client.head_object(namespace, bucket, object_name=fileName)
if headResponse.status == 200:
isExists = True
except Exception as e:
if hasattr(e, 'status') and e.status == 404:
print(f"File not found in bucket: {fileName}")
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
else:
print(f"An error occured: {e}")
return isExists

# Function to un-paginate the api call with while loop
def listObjectVersionsUnpaginated():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ads.common.object_storage_details.list_object_versions can be used instead?

objectStorageList = []
has_next_page, opc_next_page = True, None
while has_next_page:
response = self.object_storage_client.list_object_versions(
namespace_name=namespace,
bucket_name=bucket,
prefix=prefix,
fields="name,size",
page = opc_next_page
)
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
objectStorageList.extend(response.data.items)
has_next_page = response.has_next_page
opc_next_page = response.next_page
return objectStorageList

# Fetch object details and put it into the objects variable
objectStorageList = []
if files == None:
objectStorageList = listObjectVersionsUnpaginated()
else:
for fileName in files:
if checkIfFileExists(fileName=fileName):
objectStorageList.append(self.object_storage_client.list_object_versions(
namespace_name=namespace,
bucket_name=bucket,
prefix=fileName,
fields="name,size",
).data.items[0])

objects = [{
"name": obj.name,
"version": obj.version_id,
"sizeInBytes": obj.size
} for obj in objectStorageList if obj.size > 0]

if len(objects) == 0:
print("No files to add in the bucket: ", bucket, " with namespace: ", namespace, " and prefix: ", prefix, " file names: ", files)
return
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved

self.modelDescriptionJson['models'].append({
"namespace": namespace,
"bucketName": bucket,
"prefix": prefix,
"objects": objects
})

def remove(self, namespace, bucket, prefix=None):
def findModelIdx():
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
for idx, model in enumerate(self.modelDescriptionJson['models']):
if (model['namespace'], model['bucketName'], (model['prefix'] if ('prefix' in model) else None) ) == (namespace, bucket, prefix):
return idx
return -1

modelSearchIdx = findModelIdx()
if modelSearchIdx == -1:
return
else:
# model found case
self.modelDescriptionJson['models'].pop(modelSearchIdx)

def show(self):
print(json.dumps(self.modelDescriptionJson, indent=4))

def build(self):
print("Building...")
file_path = "resultModelDescription.json"
try:
with open(file_path, "w") as json_file:
json.dump(self.modelDescriptionJson, json_file, indent=2)
except IOError as e:
print(f"Error writing to file '{file_path}': {e}") # Handle the exception accordingly, e.g., log the error, retry writing, etc.
except Exception as e:
print(f"An unexpected error occurred: {e}") # Handle other unexpected exceptions
print("Model Artifact stored at location: 'resultModelDescription.json'")
return os.path.abspath(file_path)

def save(self, project_ocid, compartment_ocid, display_name=None):
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
display_name = 'Created by MMS SDK on ' + datetime.datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z') if (display_name == None) else display_name
customMetadataList = [
Metadata(key="modelDescription", value = "true")
]
model_details = oci.data_science.models.CreateModelDetails(
VipulMascarenhas marked this conversation as resolved.
Show resolved Hide resolved
compartment_id = compartment_ocid,
project_id = project_ocid,
display_name = display_name,
custom_metadata_list = customMetadataList
)
print("Created model details")
model = self.data_science_client.create_model(model_details)
print("Created model")
self.data_science_client.create_model_artifact(
model.data.id,
json.dumps(self.modelDescriptionJson),
content_disposition='attachment; filename="modelDescription.json"'
)
print('Successfully created model with OCID: ', model.data.id)
return model.data.id