Mappings:
  RegionMap:
    eu-north-1:
      s3bucket: aws-blogs-artifacts-public
    ap-south-1:
      s3bucket: aws-blogs-artifacts-public
    eu-west-3:
      s3bucket: aws-blogs-artifacts-public
    us-east-2:
      s3bucket: aws-blogs-artifacts-public
    eu-west-1:
      s3bucket: aws-blogs-artifacts-public
    eu-central-1:
      s3bucket: aws-blogs-artifacts-public
    sa-east-1:
      s3bucket: aws-blogs-artifacts-public
    us-east-1:
      s3bucket: aws-blogs-artifacts-public
    ap-northeast-2:
      s3bucket: aws-blogs-artifacts-public
    ap-northeast-3:
      s3bucket: aws-blogs-artifacts-public
    eu-west-2:
      s3bucket: aws-blogs-artifacts-public
    ap-northeast-1:
      s3bucket: aws-blogs-artifacts-public
    us-west-2:
      s3bucket: aws-blogs-artifacts-public
    us-west-1:
      s3bucket: aws-blogs-artifacts-public
    ap-southeast-1:
      s3bucket: aws-blogs-artifacts-public
    ap-southeast-2:
      s3bucket: aws-blogs-artifacts-public
    ca-central-1:
      s3bucket: aws-blogs-artifacts-public
Resources:
  assetbkt:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: BucketOwnerFullControl
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      VersioningConfiguration:
        Status: Enabled
  BasicParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: hcls-blog-s3-bucket
      Type: String
      Value: !Ref assetbkt
      Description: SSM Parameter for storing HCLS clinical trial blogpost S3 bucket name
  lambdarole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: "2012-10-17"
      Description: HCLS clinical trial blogpost Lambda Role
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonBedrockFullAccess'
        - 'arn:aws:iam::aws:policy/AmazonPollyFullAccess'
        - 'arn:aws:iam::aws:policy/AmazonTranscribeFullAccess'
        - 'arn:aws:iam::aws:policy/CloudWatchFullAccessV2'
      Policies:
        - PolicyDocument:
            Statement:
              - Action: kms:*
                Effect: Allow
                Resource: "*"
            Version: "2012-10-17"
          PolicyName: AllowKMSAccess
        - PolicyDocument:
            Statement:
              - Action: ssm:GetParameter
                Effect: Allow
                Resource:
                  Fn::Join:
                    - ""
                    - - "arn:aws:ssm:"
                      - Ref: AWS::Region
                      - ":"
                      - Ref: AWS::AccountId
                      - :parameter/*
            Version: "2012-10-17"
          PolicyName: GetSSMParameter
        - PolicyDocument:
            Statement:
              - Action: lambda:InvokeFunction
                Effect: Allow
                Resource:
                  Fn::Join:
                    - ""
                    - - "arn:aws:lambda:"
                      - Ref: AWS::Region
                      - ":"
                      - Ref: AWS::AccountId
                      - :function:*
            Version: "2012-10-17"
          PolicyName: InvokeLambdaFunction
        - PolicyDocument:
            Statement:
              - Action:
                  - s3:DeleteObject
                  - s3:DeleteObjectTagging
                  - s3:GetObject
                  - s3:GetObjectTagging
                  - s3:ListBucket
                  - s3:PutObject
                  - s3:PutObjectAcl
                  - s3:PutObjectTagging
                  - s3:PutBucketNotification
                  - s3:GetBucketNotification
                Effect: Allow
                Resource:
                  - Fn::Join:
                      - ""
                      - - "arn:aws:s3:::"
                        - Ref: assetbkt
                        - /*
                  - Fn::Join:
                      - ""
                      - - "arn:aws:s3:::"
                        - Ref: assetbkt
            Version: "2012-10-17"
          PolicyName: s3_bucket_access
        - PolicyDocument:
            Statement:
              - Action:
                  - s3:GetObject
                  - s3:GetObjectTagging
                  - s3:ListBucket
                Effect: Allow
                Resource:
                  - Fn::Join:
                      - ""
                      - - "arn:aws:s3:::"
                        - !FindInMap [RegionMap, !Ref "AWS::Region", s3bucket]
                        - /*
                  - Fn::Join:
                      - ""
                      - - "arn:aws:s3:::"
                        - !FindInMap [RegionMap, !Ref "AWS::Region", s3bucket]
            Version: "2012-10-17"
          PolicyName: s3_workshop_bucket_access
        - PolicyDocument:
            Statement:
              - Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:DescribeLogGroups
                  - logs:GetLogEvents
                  - logs:GetLogGroupFields
                  - logs:GetLogRecord
                  - logs:GetQueryResults
                  - logs:PutLogEvents
                Effect: Allow
                Resource: "*"
            Version: "2012-10-17"
          PolicyName: logs_access
        - PolicyDocument:
            Statement:
              - Action: cloudwatch:*
                Effect: Allow
                Resource: "*"
            Version: "2012-10-17"
          PolicyName: cloud_watch
  audiototextLambda:
    Type: AWS::Lambda::Function
    Properties:
      Handler: hcls_clinical_trial_audio_to_text.lambda_handler
      FunctionName: hcls_clinical_trial_audio_to_text
      Role:
        Fn::GetAtt:
          - lambdarole
          - Arn
      Code:
        S3Bucket: !FindInMap [RegionMap, !Ref "AWS::Region", s3bucket]
        S3Key: ML-17371/hcls_clinical_trial_audio_to_text.zip
      Runtime: python3.10
      Timeout: 600
  hclsclinicaltrialLambda:
    Type: AWS::Lambda::Function
    Properties:
      Handler: hcls_clinical_trial_generative_ai_analysis.lambda_handler
      FunctionName: hcls_clinical_trial_generative_ai_analysis
      Role:
        Fn::GetAtt:
          - lambdarole
          - Arn
      Code:
        S3Bucket: !FindInMap [ RegionMap, !Ref "AWS::Region", s3bucket ]
        S3Key: ML-17371/hcls_clinical_trial_generative_ai_analysis.zip
      Runtime: python3.10
      Timeout: 600
  s3LambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt audiototextLambda.Arn
      Action: lambda:InvokeFunction
      Principal: s3.amazonaws.com
      SourceAccount: !Ref 'AWS::AccountId'
      SourceArn: !GetAtt assetbkt.Arn
  CustomResourceLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Handler: index.lambda_handler
      Role: !GetAtt lambdarole.Arn
      Code:
        ZipFile: |

            from __future__ import print_function
            import json
            import boto3
            import cfnresponse
            
            SUCCESS = "SUCCESS"
            FAILED = "FAILED"
            
            print('Loading function')
            s3 = boto3.resource('s3')
            s3_client = boto3.client('s3')
            
            def lambda_handler(event, context):
                print("Received event: " + json.dumps(event, indent=2))
                responseData={}
                try:
                    if event['RequestType'] == 'Delete':
                        print("Request Type:",event['RequestType'])
                        Bucket=event['ResourceProperties']['Bucket']
                        delete_notification(Bucket)
                        print("Sending response to custom resource after Delete")
                    elif event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
                        print("Request Type:",event['RequestType'])
                        LambdaArn=event['ResourceProperties']['LambdaArn']
                        Bucket=event['ResourceProperties']['Bucket']
                        Source_Bucket=event['ResourceProperties']['SourceBucket']
                        add_notification(LambdaArn, Bucket)
                        responseData={'Bucket':Bucket}
                        add_prefix(Bucket)
                        upload_files(Bucket, Source_Bucket)
                        print("Sending response to custom resource")
                    responseStatus = 'SUCCESS'
                except Exception as e:
                    print('Failed to process:', e)
                    responseStatus = 'FAILED'
                    responseData = {'Failure': 'Something bad happened.'}
                cfnresponse.send(event, context, responseStatus, responseData, "CustomResourcePhysicalID")

            def add_notification(LambdaArn, Bucket):
                bucket_notification = s3.BucketNotification(Bucket)
                response = bucket_notification.put(
                  NotificationConfiguration={
                    'LambdaFunctionConfigurations': [
                      {
                          'LambdaFunctionArn': LambdaArn,
                          'Events': ['s3:ObjectCreated:*'],
                          'Filter': {
                            'Key': {'FilterRules': [{'Name': 'suffix', 'Value': '.mp3'}, {'Name': 'prefix','Value': 'hcls-framework/input-audio/'}]}
                          }
                      }
                    ]
                  }
                )
                print("Put request completed....")
              
              
            def delete_notification(Bucket):
                bucket_notification = s3.BucketNotification(Bucket)
                response = bucket_notification.put(
                    NotificationConfiguration={}
                )
                print("Delete request completed....")
          
          
            def add_prefix(Bucket):
                s3_folder_list = ['hcls-framework/sample-input-audio', 'hcls-framework/input-audio', 'hcls-framework/input-text', 'hcls-framework/output-text']
                for folder_name in s3_folder_list:
                    s3_client.put_object(Bucket=Bucket, Key=(folder_name + '/'))
                    print(f"folder_name: {folder_name} created in the s3 bucket: {Bucket}")
          
            
            def upload_files(Bucket, Source_Bucket):
                s3_client.copy_object(
                      Bucket=Bucket,
                      CopySource=Source_Bucket + '/ML-17371/Interview-1.mp3',
                      Key='hcls-framework/sample-input-audio/Interview-1.mp3',
                      ACL='bucket-owner-full-control',
                      StorageClass='STANDARD'
                )
                print("hcls-framework/sample-input-audio/Interview-1.mp3 uploaded to s3")
                
                s3_client.copy_object(
                      Bucket=Bucket,
                      CopySource=Source_Bucket + '/ML-17371/Interview-2.mp3',
                      Key='hcls-framework/sample-input-audio/Interview-2.mp3',
                      ACL='bucket-owner-full-control',
                      StorageClass='STANDARD'
                )
                print("hcls-framework/sample-input-audio/Interview-2.mp3 uploaded to s3")
          
                s3_client.copy_object(
                      Bucket=Bucket,
                      CopySource=Source_Bucket + '/ML-17371/Interview-3.mp3',
                      Key='hcls-framework/sample-input-audio/Interview-3.mp3',
                      ACL='bucket-owner-full-control',
                      StorageClass='STANDARD'
                )
                print("hcls-framework/sample-input-audio/Interview-2.mp3 uploaded to s3")
          
                s3_client.copy_object(
                      Bucket=Bucket,
                      CopySource=Source_Bucket + '/ML-17371/Interview-3.mp3',
                      Key='hcls-framework/sample-input-audio/Interview-3.mp3',
                      ACL='bucket-owner-full-control',
                      StorageClass='STANDARD'
                )
                print("hcls-framework/sample-input-audio/Interview-3.mp3 uploaded to s3")
          
                s3_client.copy_object(
                      Bucket=Bucket,
                      CopySource=Source_Bucket + '/ML-17371/Interview-4.mp3',
                      Key='hcls-framework/sample-input-audio/Interview-4.mp3',
                      ACL='bucket-owner-full-control',
                      StorageClass='STANDARD'
                )
                print("hcls-framework/sample-input-audio/Interview-4.mp3 uploaded to s3")
          
                s3_client.copy_object(
                      Bucket=Bucket,
                      CopySource=Source_Bucket + '/ML-17371/Interview-5.mp3',
                      Key='hcls-framework/sample-input-audio/Interview-5.mp3',
                      ACL='bucket-owner-full-control',
                      StorageClass='STANDARD'
                )
                print("hcls-framework/sample-input-audio/Interview-5.mp3 uploaded to s3")

      Runtime: python3.9
      Timeout: 120
  LambdaTrigger:
    Type: 'Custom::LambdaTrigger'
    DependsOn: s3LambdaPermission
    Properties:
      ServiceToken: !GetAtt CustomResourceLambdaFunction.Arn
      LambdaArn: !GetAtt audiototextLambda.Arn
      Bucket: !Ref assetbkt
      SourceBucket: !FindInMap [RegionMap, !Ref "AWS::Region", s3bucket]
Outputs:
  BlogpostS3Bucket:
    Description: HCLS clinical trial blogpost S3 bucket name
    Value: !Ref assetbkt

