text: # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  #
  # Licensed under the Apache License, Version 2.0 (the "License").
  # You may not use this file except in compliance with the License.
  # A copy of the License is located at
  #
  #     http://www.apache.org/licenses/LICENSE-2.0
  #
  # or in the "license" file accompanying this file. This file is distributed 
  # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 
  # express or implied. See the License for the specific language governing 
  # permissions and limitations under the License.
  from __future__ import absolute_import
  
  from sagemaker.utils import base_name_from_image
  from sagemaker.sklearn.estimator import SKLearn
  from sagemaker.model import Model
  from sagemaker.pipeline import PipelineModel
  
  from stepfunctions.steps import TrainingStep, TransformStep, ModelStep, EndpointConfigStep, EndpointStep, Chain, Fail, Catch
  from stepfunctions.workflow import Workflow
  from stepfunctions.template.pipeline.common import StepId, WorkflowTemplate
  
  
  class TrainingPipeline(WorkflowTemplate):
  
      """
      Creates a standard training pipeline with the following steps in order:
  
          1. Train estimator
          2. Create estimator model
          3. Endpoint configuration
          4. Deploy model
      """
  
      __allowed_kwargs = ('pipeline_name',)
      
      def __init__(self, estimator, role, inputs, s3_bucket, client=None, **kwargs):
          """
          Args:
              estimator (sagemaker.estimator.EstimatorBase): The estimator to use for training. Can be a BYO estimator, Framework estimator or Amazon algorithm estimator.
              role (str): An AWS IAM role (either name or full Amazon Resource Name (ARN)). This role is used to create, manage, and execute the Step Functions workflows.
              inputs: Information about the training data. Please refer to the `fit()` method of the associated estimator, as this can take any of the following forms:
  
                  * (str) - The S3 location where training data is saved.
                  * (dict[str, str] or dict[str, `sagemaker.inputs.TrainingInput`]) - If using multiple channels for training data, you can specify a dict mapping channel names to strings or `sagemaker.inputs.TrainingInput` objects.
                  * (`sagemaker.inputs.TrainingInput`) - Channel configuration for S3 data sources that can provide additional information about the training dataset. See `sagemaker.inputs.TrainingInput` for full details.
                  * (`sagemaker.amazon.amazon_estimator.RecordSet`) - A collection of Amazon `Record` objects serialized and stored in S3. For use with an estimator for an Amazon algorithm.
                  * (list[`sagemaker.amazon.amazon_estimator.RecordSet`]) - A list of `sagemaker.amazon.amazon_estimator.RecordSet` objects, where each instance is a different channel of training data.
              s3_bucket (str): S3 bucket under which the output artifacts from the training job will be stored. The parent path used is built using the format: ``s3://{s3_bucket}/{pipeline_name}/models/{job_name}/``. In this format, `pipeline_name` refers to the keyword argument provided for TrainingPipeline. If a `pipeline_name` argument was not provided, one is auto-generated by the pipeline as `training-pipeline-<timestamp>`. Also, in the format, `job_name` refers to the job name provided when calling the :meth:`TrainingPipeline.run()` method.
              client (SFN.Client, optional): boto3 client to use for creating and interacting with the training pipeline in Step Functions. (default: None)
  
          Keyword Args:
              pipeline_name (str, optional): Name of the pipeline. This name will be used to name jobs (if not provided when calling execute()), models, endpoints, and S3 objects created by the pipeline. If a `pipeline_name` argument was not provided, one is auto-generated by the pipeline as `training-pipeline-<timestamp>`. (default:None)
          """
          self.estimator = estimator
          self.inputs = inputs
          
          for key in self.__class__.__allowed_kwargs:
              setattr(self, key, kwargs.pop(key, None))
  
          if not self.pipeline_name:
              self.__pipeline_name_unique = True
              self.pipeline_name = 'training-pipeline-{date}'.format(date=self._generate_timestamp())
  
          self.definition = self.build_workflow_definition()
          self.input_template = self._extract_input_template(self.definition)
  
          workflow = Workflow(name=self.pipeline_name, definition=self.definition, role=role, format_json=True, client=client)
  
          super(TrainingPipeline, self).__init__(s3_bucket=s3_bucket, workflow=workflow, role=role, client=client)
      
      def build_workflow_definition(self):
          """
          Build the workflow definition for the training pipeline with all the states involved.
  
          Returns:
              :class:`~stepfunctions.steps.states.Chain`: Workflow definition as a chain of states involved in the the training pipeline.
          """
          default_name = self.pipeline_name
  
          instance_type = self.estimator.instance_type
          instance_count = self.estimator.instance_count
  
          training_step = TrainingStep(
              StepId.Train.value,
              estimator=self.estimator,
              job_name=default_name + '/estimator-source',
              data=self.inputs,
          )
  
          model = self.estimator.create_model()
          model_step = ModelStep(
              StepId.CreateModel.value,
              instance_type=instance_type,
              model=model,
              model_name=default_name
          )
  
          endpoint_config_step = EndpointConfigStep(
              StepId.ConfigureEndpoint.value,
              endpoint_config_name=default_name,
              model_name=default_name,
              initial_instance_count=instance_count,
              instance_type=instance_type
          )
          deploy_step = EndpointStep(
              StepId.Deploy.value,
              endpoint_name=default_name,
              endpoint_config_name=default_name,
          )
  
          return Chain([training_step, model_step, endpoint_config_step, deploy_step])
      
      def execute(self, job_name=None, hyperparameters=None):
          """
          Run the training pipeline.
          
          Args:
              job_name (str, optional): Name for the training job. If one is not provided, a job name will be auto-generated. (default: None)
              hyperparameters (dict, optional): Hyperparameters for the estimator training. (default: None)
          
          Returns:
              :py:class:`~stepfunctions.workflow.Execution`: Running instance of the training pipeline.
          """
          inputs = self.input_template.copy()
          
          if hyperparameters is not None:
              inputs[StepId.Train.value]['HyperParameters'] = {
                  k: str(v) for k, v in hyperparameters.items()
              }
          
          if job_name is None:
              job_name = '{base_name}-{timestamp}'.format(base_name='training-pipeline', timestamp=self._generate_timestamp())
          
          # Configure training and model
          inputs[StepId.Train.value]['TrainingJobName'] = 'estimator-' + job_name
          inputs[StepId.Train.value]['OutputDataConfig']['S3OutputPath'] = 's3://{s3_bucket}/{pipeline_name}/models'.format(
              s3_bucket=self.s3_bucket,
              pipeline_name=self.workflow.name
          )
          inputs[StepId.CreateModel.value]['ModelName'] = job_name
  
          # Configure endpoint
          inputs[StepId.ConfigureEndpoint.value]['EndpointConfigName'] = job_name
          for variant in inputs[StepId.ConfigureEndpoint.value]['ProductionVariants']:
              variant['ModelName'] = job_name
          inputs[StepId.Deploy.value]['EndpointConfigName'] = job_name
          inputs[StepId.Deploy.value]['EndpointName'] = job_name
          
          # Configure the path to model artifact
          inputs[StepId.CreateModel.value]['PrimaryContainer']['ModelDataUrl'] = '{s3_uri}/{job}/output/model.tar.gz'.format(
              s3_uri=inputs[StepId.Train.value]['OutputDataConfig']['S3OutputPath'],
              job=inputs[StepId.Train.value]['TrainingJobName']
          )
          
          return self.workflow.execute(inputs=inputs, name=job_name)
  