import boto3 import gzip import tarfile import io import os from joblib import load…
- User
import boto3 import gzip import tarfile import io import os from joblib import load import pandas as pd import numpy as np from sklearn.metrics.pairwise import cosine_similarity
Previouly we made sure that the LSH class is defined in a separate module (a .py file) instead of the Jupyter notebook or the main script. Let's say we save it in lsh_model.py.
So class LSH is defined in the module where we are trying to load the pickled object.
Python's pickle module needs to find the same class definition during loading as was present during saving.
from lsh_model import LSH
from lsh_model import rank_top_similar_items
Initialize a boto3 S3 client
s3 = boto3.client('s3')
def initialize(context): # Specify the name of the S3 bucket and the key of the .tar.gz file bucket_name = "nike-geminipoc-test-serverless-deployments" object_key = "serverless/gemini-poc-opensearch-api-es/test/lsh_model_tongue_lining.tar.gz"
# Parse the base model and data filenames base_with_extension = os.path.basename(object_key) base_no_extension = base_with_extension.rsplit(".", 2)[0] model_file_path = f"{base_no_extension}.joblib" data_file_path = f"{base_no_extension}.pkl" # Check if the files already exist and skip downloading if so if not os.path.isfile(model_file_path) or not os.path.isfile(data_file_path): # Download the .tar.gz file from S3 to an in-memory buffer if files do not exist buffer = io.BytesIO() s3.download_fileobj(bucket_name, object_key, buffer) buffer.seek(0) # Use the gzip library to decompress the buffer decompressed_buffer = io.BytesIO(gzip.decompress(buffer.read())) decompressed_buffer.seek(0) # Use the tarfile library to extract the contents of the .tar.gz file with tarfile.open(fileobj=decompressed_buffer) as tar: tar.extractall() else: print("Model and data files already exist locally, skipping download.") # Load the model and data print(f"Reading model from: {model_file_path}") lsh_model_loaded = load(model_file_path) print(f"Reading data from: {data_file_path}") data = pd.read_pickle(data_file_path) return lsh_model_loaded, datadef inference(model, data, query_id, top_n=20):
# Findd similar IDs and rank them similar_ids = model.query(data.loc[query_id]) top_n_similar_ids = rank_top_similar_items(data, query_id, similar_ids, top_n=top_n) return top_n_similar_idsGet the ids
payload = {"part_name": "tongue_lining", "query_id": '61a99df7-f298-43ac-ad41-bed28b109a31'} context = payload["part_name"] query_id_ =payload["query_id"]
initialize
model_, data_ = initialize(context)
Operate Innference
top_n_similar_ids = inference(model_, data_, query_id_) print(top_n_similar_ids)
- Assistant
This script performs the following operations:
- Initializes a connection to an Amazon S3 bucket and downloads a compressed file containing a machine learning model and relevant data.