# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: conda_python3
#     language: python
#     name: conda_python3
# ---

# # Lab Environment for BYOA Pipeline
#
# This notebook instance will act as the lab environment for setting up and triggering changes to our pipeline.  This is being used to provide a consistent environment, gain some familiarity with Amazon SageMaker Notebook Instances, and to avoid any issues with debugging individual laptop configurations during the workshop. 
#
# PLEASE review the [sample notebook](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/scikit_bring_your_own/scikit_bring_your_own.ipynb) for detailed documentation on the model being built
#
# ---

# ## Step 1:  View the Data
#
#   In the code cell below, we'll take a look at the training/test/validation datasets and then upload them to S3. Just as the sample notebook referenced above, For the purposes of this example, we're using some the classic [Iris Flower](https://en.wikipedia.org/wiki/Iris_flower_data_set) dataset, which we have included in the local notebook instance under the ./data folder.

# +
import pandas as pd
train_data = pd.read_csv('./data/1-train/train/iris.csv', sep=',')
pd.set_option('display.max_columns', 500)     # Make sure we can see all of the columns
pd.set_option('display.max_rows', 5)         # Keep the output on one page
print('\nTraining Data\n', train_data)

smoketest_data = pd.read_csv('./data/1-train/smoketest/iris.csv', sep=',')
pd.set_option('display.max_columns', 500)     # Make sure we can see all of the columns
pd.set_option('display.max_rows', 5)         # Keep the output on one page
print('\nSmoke Test Data\n', smoketest_data)

validation_data = pd.read_csv('./data/1-train/validation/iris.csv', sep=',')
pd.set_option('display.max_columns', 500)     # Make sure we can see all of the columns
pd.set_option('display.max_rows', 5)         # Keep the output on one page
print('\nValidation Data\n', validation_data)

# -

# ---
# ## Step 2:  Upload Data to S3 
#
# We will utilize this notebook to perform some of the setup that will be required to trigger the first execution of our pipeline.   In this second step in our Machine Learning pipeline, we are going to simulate what would typically be the last step in an Analytics pipeline of creating datasets. 
#
# To accomplish this, we will actually be uploading data from our local notebook instance (data can be found under /data/1-train/*) to S3.  In a typical scenario, this would be done through your analytics pipeline.  We will use the S3 bucket that was created through the CloudFormation template we launched at the beginning of the lab. You can validate the S3 bucket exists by:
#   1. Going to the [S3 Service](https://s3.console.aws.amazon.com/s3/) inside the AWS Console
#   2. Find the name of the S3 data bucket created by the CloudFormation template: mlops-data-*yourintials*-*randomid*
#   
# In the code cell below, we'll take a look at the training/test/validation datasets and then upload them to S3. 
#
#    ### UPDATE THE BUCKET NAME BELOW BEFORE EXECUTING THE CELL

# +
import os
import boto3
import re
import time

# UPDATE THE NAME OF THE BUCKET TO MATCH THE ONE WE CREATED THROUGH THE CLOUDFORMATION TEMPLATE
# Example: mlops-data-jdd-df4d4850
#bucket = 'mlops-data-<yourinitials>-<generated id>'
bucket = 'mlops-data-jdd-d4d740c0'


from sagemaker import get_execution_role

role = get_execution_role()
region = boto3.Session().region_name


trainfilename = 'train/train.csv'
smoketestfilename = 'smoketest/smoketest.csv'
validationfilename = 'validation/validation.csv'


s3 = boto3.resource('s3')

s3.meta.client.upload_file('./data/1-train/train/iris.csv', bucket, trainfilename)
s3.meta.client.upload_file('./data/1-train/smoketest/iris.csv', bucket, smoketestfilename)
s3.meta.client.upload_file('./data/1-train/validation/iris.csv', bucket, validationfilename)
# -

# ---
# ## Step 3:  Commit Training Code To Trigger Pipeline Build
#
# In this step, we are going to trigger an execution of the pipeline by committing our training code to the CodeCommit repository that was setup as part of the CloudFormation stack.  The CodeCommit repository created was associated with this SageMaker Notebook Instance via a setting in the CloudFormation Stack using the [SageMaker Notebook Instance Git Association](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-repo.html) feature.
#
# The pipeline is currently setup to trigger on a commit to the master branch; however, this should be adjusted in a real-world scenario based on your branching strategy. 
#
# The CodeCommit repository created can be viewed by:
#   1. Going to the [CodeCommit Service](https://console.aws.amazon.com/codesuite/codecommit/repositories) inside the AWS Console
#   2. Find the name of the repository created by the CloudFormation template: mlops-codecommit-byo-*yourinitials*
#   
# **UPDATE** Ensure you update the cell below where noted prior to executing 

# +
# View the CodeCommit repository -
# This Git integration was configured as part of the creation of the notebook instance in the CloudFormation stack.

# The following will return the CodeCommit repository that has been configured with this notebook and will be used 
# for the source control repository during this workshop. 

# Ensure remote repo is setup
# !git remote -v

# !git config --global user.name "<NAME>"
# !git config --global user.email <EMAIL>
# -

# ### Commit training code to the CodeCommit repository to trigger the execution of the CodePipeline

# !git pull
# !git add ./model-code/*
# !git commit -m "Initial add of model code to CodeCommit Repo"
# !git push origin master

# ----
#
# ## Step 4:  Monitor CodePipeline Execution
#
# The code above will trigger the execution of your CodePipeline. You can monitor progress of the pipeline execution in the [CodePipeline dashboard](https://console.aws.amazon.com/codesuite/codepipeline/pipelines).
#
# You can also validate that your code is now committed to the CodeCommit repository in the [CodeCommit dashboard](https://console.aws.amazon.com/codesuite/codecommit/repositories)
#
# As the pipeline is executing information is being logged to [Cloudwatch logs](https://console.aws.amazon.com/cloudwatch/logs).  Explore the logs for your Lambda functions (/aws/lambda/MLOps-BYO*) as well as output logs from SageMaker (/aws/sagemaker/*)
#
#
# Note: It will take awhile to execute all the way through the pipeline.  Please don't proceed to the next step until the last stage is shows **'succeeded'**

# --- 
#
# ## Step 5: Edit CodePipeline Triggers to add model retraining
#
# In the steps above, we demonstrated how you can trigger the pipeline when new code is committed to CodeCommit.  As you continue to modify your training/inference code, you essentially re-execute the cell above to commit new code and trigger another execution of the pipeline.  Although we are using a notebook instance for the purposes of the workshop, the commit to a source code repository above can happen in your local environment and/or IDEs of choice. 
#
# In this step, we want to modify the pipeline to add the capability to not only trigger based off code changes but to also trigger a retraining cycle in the event of receiving new training data. If the file/object containing the training data is a single object that will be inclusive of all training data you want to use, you can trigger CodePipeline based on the object itself. However, if you are looking to training incrementally or if your analytics pipeline puts new data to your S3 bucket as deltas then you need to have a trigger mechanism included in your analytics pipeline that notifies CodePipeline it is time to retrain. 
#
# To simplify the setup for this workshop, we are going to trigger based on a new training dataset that is inclusive of all the data we want to retrain with. 
#
#    1. Go to your [CodePipeline Pipeline](https://console.aws.amazon.com/codesuite/codepipeline/pipelines) 
#
#    2. Click on the link to your pipeline (i.e. MLOps-BYO-BuildPipeline*)
#    
#    3. Click the **Edit** Button 
#    
#    4. Inside **Edit:Source** , click the **Edit stage** button --> then Click **Add Action**
#    
#    5. Under Edit Action:
#    
#        * **Action Name** : RetrainData
#        
#        * **Action Provider** : Source - S3
#        
#        * **Bucket** : *Enter the name of your S3 data bucket* Example: mlops-data-jdd-d4d740c0
#        
#        * **S3 object key** : train/train.csv
#        
#        * **Output Artifacts** : RetrainDataIn
#        
#        
#    6. Validate your screen contains all information as shown below: 
#    
#        
#        
#    7. Click **Done**
#    
#    8. Click the orange **Save** button in the upper right hand corner to save your changes, confirm changes and hit **Save** again.

# Because we may not want rebuild the training/inference container image in the case where we only want to retrain the model, you could optionally create a separate retraining pipeline that excludes the rebuild of the image.  Depending on what you are using for orchestration across your pipeline, you can accomplish this through a single or multiple pipelines. 
#

# ----
# ## Step 6: Trigger retraining based on new data
#  
# Let's test our new CodePipeline trigger by adding new training data to our S3 data bucket.  The S3 data bucket is setup with versioning enabled.  

# +
trainfilename = 'train/train.csv'

s3 = boto3.resource('s3')

s3.meta.client.upload_file('./data/1-train/train/iris-2.csv', bucket, trainfilename)
# -

# After executing the cell above, you will see a new trigger for pipeline execution when you click on the link to your [pipeline](https://console.aws.amazon.com/codesuite/codepipeline/pipelines)
#

# ---
#
# ## Step 7: Clean-Up
#
#
# Return to the [README.md](https://github.com/aws-samples/amazon-sagemaker-devops-with-ml/2-Bring-Your-Own/README.md) to complete the environment cleanup instructions. 

# # CONGRATULATIONS! 
#
# You've built a basic pipeline for the use case of bringing your own algorithm/training/inference code to SageMaker.  This pipeline can act as a starting point for building in additional quality gates such as container scans, manual approvals, and additional evaluation/logging capabilities.   Another common extension to the pipeline may be creating/updating your API serving predictions through API Gateway.  

StarcoderdataJupyterScriptsDedupFiltered