ferruzzi commented on a change in pull request #21673:
URL: https://github.com/apache/airflow/pull/21673#discussion_r813398178



##########
File path: docs/apache-airflow-providers-amazon/operators/sagemaker.rst
##########
@@ -0,0 +1,71 @@
+ .. Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+ ..   http://www.apache.org/licenses/LICENSE-2.0
+
+ .. Unless required by applicable law or agreed to in writing,
+    software distributed under the License 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.
+
+
+Amazon Sagemaker Operators

Review comment:
       ```suggestion
   Amazon SageMaker Operators
   ```
   
   Nitpick:  Here and elsewhere, `Amazon SageMaker` is the proper/official 
naming convention.

##########
File path: airflow/providers/amazon/aws/example_dags/example_sagemaker.py
##########
@@ -0,0 +1,179 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License 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 datetime import datetime
+from os import environ
+
+from airflow import DAG
+from airflow.providers.amazon.aws.operators.sagemaker import (
+    SageMakerDeleteModelOperator,
+    SageMakerModelOperator,
+    SageMakerProcessingOperator,
+    SageMakerTrainingOperator,
+    SageMakerTransformOperator,
+)
+
+model_name = "sample_model"
+training_job_name = 'sample_training'
+image_uri = environ.get('ECR_IMAGE_URI', 
'123456789012.dkr.ecr.us-east-1.amazonaws.com/repo_name')
+s3_bucket = environ.get('BUCKET_NAME', 'test-airflow-12345')
+role = environ.get('SAGEMAKER_ROLE_ARN', 
'arn:aws:iam::123456789012:role/role_name')
+
+sagemaker_processing_job_config = {
+    "ProcessingJobName": "sample_processing_job",
+    "ProcessingInputs": [
+        {
+            "InputName": "input",
+            "AppManaged": False,
+            "S3Input": {
+                "S3Uri": f"s3://{s3_bucket}/preprocessing/input/",
+                "LocalPath": "/opt/ml/processing/input/",
+                "S3DataType": "S3Prefix",
+                "S3InputMode": "File",
+                "S3DataDistributionType": "FullyReplicated",
+                "S3CompressionType": "None",
+            },
+        },
+    ],
+    "ProcessingOutputConfig": {
+        "Outputs": [
+            {
+                "OutputName": "output",
+                "S3Output": {
+                    "S3Uri": f"s3://{s3_bucket}/preprocessing/output/",
+                    "LocalPath": "/opt/ml/processing/output/",
+                    "S3UploadMode": "EndOfJob",
+                },
+                "AppManaged": False,
+            }
+        ]
+    },
+    "ProcessingResources": {
+        "ClusterConfig": {
+            "InstanceCount": 1,
+            "InstanceType": "ml.m5.large",
+            "VolumeSizeInGB": 5,
+        }
+    },
+    "StoppingCondition": {"MaxRuntimeInSeconds": 3600},
+    "AppSpecification": {
+        "ImageUri": f"{image_uri}",
+        "ContainerEntrypoint": ["python3", "./preprocessing.py"],
+    },
+    "RoleArn": f"{role}",
+}
+
+sagemaker_training_job_config = {
+    "AlgorithmSpecification": {
+        "TrainingImage": f"{image_uri}",
+        "TrainingInputMode": "File",
+    },
+    "InputDataConfig": [
+        {
+            "ChannelName": "config",
+            "DataSource": {
+                "S3DataSource": {
+                    "S3DataType": "S3Prefix",
+                    "S3Uri": f"s3://{s3_bucket}/config/",
+                    "S3DataDistributionType": "FullyReplicated",
+                }
+            },
+            "CompressionType": "None",
+            "RecordWrapperType": "None",
+        },
+    ],
+    "OutputDataConfig": {
+        "KmsKeyId": "",
+        "S3OutputPath": f"s3://{s3_bucket}/training/",
+    },
+    "ResourceConfig": {
+        "InstanceType": "ml.m5.large",
+        "InstanceCount": 1,
+        "VolumeSizeInGB": 5,
+    },
+    "StoppingCondition": {"MaxRuntimeInSeconds": 6000},
+    "RoleArn": f"{role}",
+    "EnableNetworkIsolation": False,
+    "EnableInterContainerTrafficEncryption": False,
+    "EnableManagedSpotTraining": False,
+    "TrainingJobName": training_job_name,
+}
+
+sagemaker_create_model_config = {
+    "ModelName": model_name,
+    "Containers": [
+        {
+            "Image": f"{image_uri}",
+            "Mode": "SingleModel",
+            "ModelDataUrl": 
f"s3://{s3_bucket}/training/{training_job_name}/output/model.tar.gz",
+        }
+    ],
+    "ExecutionRoleArn": f"{role}",
+    "EnableNetworkIsolation": False,
+}
+
+sagemaker_inference_config = {
+    "TransformJobName": "sample_transform_job",
+    "ModelName": model_name,
+    "TransformInput": {
+        "DataSource": {
+            "S3DataSource": {
+                "S3DataType": "S3Prefix",
+                "S3Uri": f"s3://{s3_bucket}/config/config_date.yml",
+            }
+        },
+        "ContentType": "application/x-yaml",
+        "CompressionType": "None",
+        "SplitType": "None",
+    },
+    "TransformOutput": {"S3OutputPath": 
f"s3://{s3_bucket}/inferencing/output/"},
+    "TransformResources": {"InstanceType": "ml.m5.large", "InstanceCount": 1},
+}
+
+# [START howto_operator_sagemaker]
+with DAG(
+    "sample_sagemaker_dag",
+    schedule_interval=None,
+    start_date=datetime(2022, 2, 21),
+    catchup=False,
+) as dag:
+    sagemaker_processing_task = SageMakerProcessingOperator(
+        config=sagemaker_processing_job_config,
+        aws_conn_id="aws_default",

Review comment:
       Out of scope for this PR, but the Operators not having a default value 
for `aws_conn_id` is a pain, we should fix that.

##########
File path: tests/providers/amazon/aws/operators/test_sagemaker_model.py
##########
@@ -63,3 +66,17 @@ def test_execute_with_failure(self, mock_model, mock_client):
         mock_model.return_value = {'ModelArn': 'testarn', 'ResponseMetadata': 
{'HTTPStatusCode': 404}}
         with pytest.raises(AirflowException):
             self.sagemaker.execute(None)
+
+
+class TestSageMakerDeleteModelOperator(unittest.TestCase):
+    def setUp(self):
+        self.sagemaker = SageMakerDeleteModelOperator(
+            task_id='test_sagemaker_operator', 
aws_conn_id='sagemaker_test_id', model_name='test'
+        )
+
+    @mock.patch.object(SageMakerHook, 'get_conn')
+    @mock.patch.object(SageMakerHook, 'delete_model')
+    def test_model_delete(self, mock_model, mock_client):

Review comment:
       Nipick, take it or leave it, but I'd rename `mock_model` to 
`mock_delete_model` for clarity, but I suppose that's personal preference.

##########
File path: airflow/providers/amazon/aws/hooks/sagemaker.py
##########
@@ -908,3 +908,19 @@ def find_processing_job_by_name(self, processing_job_name: 
str) -> bool:
             if e.response['Error']['Code'] in ['ValidationException', 
'ResourceNotFound']:
                 return False
             raise
+
+    def delete_model(self, model_name: str):
+        """Delete Sagemaker model
+        :param model_name: (optional) name of the model
+        :return: True if Model exists and deleted else return False

Review comment:
       In general I try to keep hook behavior as close to the underlying boto 
functionality as possible.  Is there a particular reason you want to return 
True or False here when the boto call itself does not return a value?

##########
File path: airflow/providers/amazon/aws/example_dags/example_sagemaker.py
##########
@@ -0,0 +1,179 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License 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 datetime import datetime
+from os import environ
+
+from airflow import DAG
+from airflow.providers.amazon.aws.operators.sagemaker import (
+    SageMakerDeleteModelOperator,
+    SageMakerModelOperator,
+    SageMakerProcessingOperator,
+    SageMakerTrainingOperator,
+    SageMakerTransformOperator,
+)
+
+model_name = "sample_model"
+training_job_name = 'sample_training'

Review comment:
       Here and elsewhere:  Single quotes or double quotes, please pick one.  
Also, all of these variables defined before the DAG context are effectively 
globals/constants and names should be in all caps, such as `MODEL_NAME`.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to