<commit_before># Copyright 2021 The Kubeflow Authors. 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.
# 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.
"""Module for remote execution of AI Platform pipeline component."""

import argparse
import ast
from distutils import util as distutil
import inspect
import json
import os
import re
from typing import Any, Callable, Dict, Tuple, Type, TypeVar

from google.cloud import aiplatform
from google_cloud_pipeline_components.aiplatform import utils

INIT_KEY = 'init'
METHOD_KEY = 'method'
AIPLATFORM_API_VERSION = 'v1'

RESOURCE_PREFIX = {
    'bigquery': 'bq://',
    'aiplatform': 'aiplatform://',
    'google_cloud_storage': 'gs://',
    'google_cloud_storage_gcs_fuse': '/gcs/',
}


def split_args(kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
  """Splits args into constructor and method args.

    Args:
        kwargs: kwargs with parameter names preprended with init or method

    Returns:
        constructor kwargs, method kwargs
    """
  init_args = {}
  method_args = {}

  for key, arg in kwargs.items():
    if key.startswith(INIT_KEY):
      init_args[key.split('.')[-1]] = arg
    elif key.startswith(METHOD_KEY):
      method_args[key.split('.')[-1]] = arg

  return init_args, method_args


def write_to_artifact(executor_input, text):
  """Write output to local artifact and metadata path (uses GCSFuse)."""

  output_artifacts = {}
  for name, artifacts in executor_input.get('outputs', {}).get('artifacts',
                                                               {}).items():
    artifacts_list = artifacts.get('artifacts')
    if artifacts_list:
      output_artifacts[name] = artifacts_list[0]

  executor_output = {}
  if output_artifacts:
    executor_output['artifacts'] = {}
    uri_with_prefix = ''

    # TODO - Support multiple outputs, current implementation.

    # sets all output uri's to text
    for name, artifact in output_artifacts.items():
      metadata = artifact.get('metadata', {})
      # Add URI Prefix
      # "https://[location]-aiplatform.googleapis.com/API_VERSION/": For AI Platform resource names, current version is defined in AIPLATFORM_API_VERSION.
      if aiplatform.utils.RESOURCE_NAME_PATTERN.match(text):
        location = re.findall('locations/([\w\-]+)', text)[0]
        uri_with_prefix = f'https://{location}-aiplatform.googleapis.com/{AIPLATFORM_API_VERSION}/{text}'
        metadata.update({'resourceName': text})

      # "gcs://": For Google Cloud Storage resources.
      elif text.startswith(RESOURCE_PREFIX['google_cloud_storage_gcs_fuse']):
        uri_with_prefix = text.replace(
            RESOURCE_PREFIX['google_cloud_storage_gcs_fuse'],
            RESOURCE_PREFIX.get('google_cloud_storage'))

      # "bq://": For BigQuery resources.
      elif text.startswith(RESOURCE_PREFIX.get('bigquery')):
        uri_with_prefix = text
      else:
        uri_with_prefix = text

      runtime_artifact = {<commit_msg>chore(component): tmp fix missing RESOURCE_NAME_PATTERN in google-cloud-aiplatform sdk<commit_after># Copyright 2021 The Kubeflow Authors. 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.
# 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.
"""Module for remote execution of AI Platform pipeline component."""

import argparse
import ast
from distutils import util as distutil
import inspect
import json
import os
import re
from typing import Any, Callable, Dict, Tuple, Type, TypeVar

from google.cloud import aiplatform
from google_cloud_pipeline_components.aiplatform import utils

INIT_KEY = 'init'
METHOD_KEY = 'method'
AIPLATFORM_API_VERSION = 'v1'

RESOURCE_PREFIX = {
    'bigquery': 'bq://',
    'aiplatform': 'aiplatform://',
    'google_cloud_storage': 'gs://',
    'google_cloud_storage_gcs_fuse': '/gcs/',
}

RESOURCE_NAME_PATTERN = re.compile(
    r'^projects\/(?P<project>[\w-]+)\/locations\/(?P<location>[\w-]+)\/(?P<resource>[\w\-\/]+)\/(?P<id>[\w-]+)$'
)


def split_args(kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
  """Splits args into constructor and method args.

    Args:
        kwargs: kwargs with parameter names preprended with init or method

    Returns:
        constructor kwargs, method kwargs
    """
  init_args = {}
  method_args = {}

  for key, arg in kwargs.items():
    if key.startswith(INIT_KEY):
      init_args[key.split('.')[-1]] = arg
    elif key.startswith(METHOD_KEY):
      method_args[key.split('.')[-1]] = arg

  return init_args, method_args


def write_to_artifact(executor_input, text):
  """Write output to local artifact and metadata path (uses GCSFuse)."""

  output_artifacts = {}
  for name, artifacts in executor_input.get('outputs', {}).get('artifacts',
                                                               {}).items():
    artifacts_list = artifacts.get('artifacts')
    if artifacts_list:
      output_artifacts[name] = artifacts_list[0]

  executor_output = {}
  if output_artifacts:
    executor_output['artifacts'] = {}
    uri_with_prefix = ''

    # TODO - Support multiple outputs, current implementation.

    # sets all output uri's to text
    for name, artifact in output_artifacts.items():
      metadata = artifact.get('metadata', {})
      # Add URI Prefix
      # "https://[location]-aiplatform.googleapis.com/API_VERSION/": For AI Platform resource names, current version is defined in AIPLATFORM_API_VERSION.
      if RESOURCE_NAME_PATTERN.match(text):
        location = re.findall('locations/([\w\-]+)', text)[0]
        uri_with_prefix = f'https://{location}-aiplatform.googleapis.com/{AIPLATFORM_API_VERSION}/{text}'
        metadata.update({'resourceName': text})

      # "gcs://": For Google Cloud Storage resources.
      elif text.startswith(RESOURCE_PREFIX['google_cloud_storage_gcs_fuse']):
        uri_with_prefix = text.replace(
            RESOURCE_PREFIX['google_cloud_storage_gcs_fuse'],
            RESOURCE_PREFIX.get('google_cloud_storage'))

      # "bq://": For BigQuery resources.
      elif text.startswith(RESOURCE_PREFIX.get('bigquery')):
        uri_with_prefix = text
      else:
        uri_with_prefix = text

      runtime_artifact = {
{'fraction_non_alphanumeric': 0.11560203504804975, 'fraction_numerical': 0.003674392312040701, 'mean_word_length': 3.5307298335467348, 'pattern_counts': {'":': 6, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4560447', 'n_tokens_mistral': 2137, 'n_tokens_neox': 2073, 'n_words': 598}