<commit_before># Lint as: python3
# Copyright 2019 Google LLC
#
# 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
#
#     https://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.
"""Predict extractor for TFJS models."""

from __future__ import absolute_import
from __future__ import division
# Standard __future__ imports
from __future__ import print_function

import collections
import copy
import json
import os
import subprocess
import tempfile
from typing import Dict, List, Optional, Union, Sequence, Text

import uuid

import apache_beam as beam
import numpy as np
import tensorflow as tf
from tensorflow_model_analysis import config
from tensorflow_model_analysis import constants
from tensorflow_model_analysis import model_util
from tensorflow_model_analysis import types
from tensorflow_model_analysis.extractors import extractor
from tensorflow_model_analysis.extractors.tfjs_predict_extractor_util import get_tfjs_binary

_TFJS_PREDICT_EXTRACTOR_STAGE_NAME = 'ExtractTFJSPredictions'

_MODELS_SUBDIR = 'Models'
_EXAMPLES_SUBDIR = 'Input_Examples'
_OUTPUTS_SUBDIR = 'Inference_Results'

_MODEL_JSON = 'model.json'
_DATA_JSON = 'data.json'
_DTYPE_JSON = 'dtype.json'
_SHAPE_JSON = 'shape.json'
_TF_INPUT_NAME_JSON = 'tf_input_name.json'


# TODO(b/149981535) Determine if we should merge with RunInference.
@beam.typehints.with_input_types(beam.typehints.List[types.Extracts])
@beam.typehints.with_output_types(types.Extracts)
class _TFJSPredictionDoFn(model_util.BatchReducibleDoFnWithModels):
  """A DoFn that loads tfjs models and predicts."""

  def __init__(self, eval_config: config.EvalConfig,
               eval_shared_models: Dict[Text, types.EvalSharedModel]) -> None:
    super(_TFJSPredictionDoFn, self).__init__(
        {k: v.model_loader for k, v in eval_shared_models.items()})
    self._eval_config = eval_config
    self._src_model_paths = {
        k: v.model_path for k, v in eval_shared_models.items()
    }

  def setup(self):
    super(_TFJSPredictionDoFn, self).setup()
    self._binary_path = get_tfjs_binary()

    base_path = tempfile.mkdtemp()
    base_model_path = os.path.join(base_path, _MODELS_SUBDIR)

    self._model_properties = {}
    for model_name, model_path in self._src_model_paths.items():
      with tf.io.gfile.GFile(os.path.join(model_path, _MODEL_JSON)) as f:
        model_json = json.load(f)
        model_signature = model_json['userDefinedMetadata']['signature']
        model_inputs = {}
        for k, v in model_signature['inputs'].items():
          model_inputs[k] = [int(i['size']) for i in v['tensorShape']['dim']]

        model_outputs = {}
        for k, v in model_signature['outputs'].items():
          model_outputs[k] = [int(i['size']) for i in v['tensorShape']['dim']]

      cur_model_path = os.path.join(base_model_path, model_name)
      self._model_properties[model_name] = {
          'inputs': model_inputs,
          'outputs': model_outputs,
          'path': cur_model_path
      }

      # We copy models to local tmp storage so that the tfjs binary can
      # access them.
      tf.io.gfile.makedirs(cur_model_path)
      for directory, _, files in tf.io.gfile.walk(model_path):
        cur_path = os.path.join(cur_model_path,
                                os.path.relpath(directory, model_path))
        tf.io.gfile.makedirs(cur_path)
        for f in files:
          src_path = os.path.join(directory, f)
          tf.io.gfile.copy(src_path, os.path.join(cur_path, f))

  def _batch_reducible_process(
      self, elements: List[types.Extracts]) -> Sequence[types.Extracts]:<commit_msg>Fix for breaking change in TFJS to remove 'userDefinedMetadata'.<commit_after># Lint as: python3
# Copyright 2019 Google LLC
#
# 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
#
#     https://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.
"""Predict extractor for TFJS models."""

from __future__ import absolute_import
from __future__ import division
# Standard __future__ imports
from __future__ import print_function

import collections
import copy
import json
import os
import subprocess
import tempfile
from typing import Dict, List, Optional, Union, Sequence, Text

import uuid

import apache_beam as beam
import numpy as np
import tensorflow as tf
from tensorflow_model_analysis import config
from tensorflow_model_analysis import constants
from tensorflow_model_analysis import model_util
from tensorflow_model_analysis import types
from tensorflow_model_analysis.extractors import extractor
from tensorflow_model_analysis.extractors.tfjs_predict_extractor_util import get_tfjs_binary

_TFJS_PREDICT_EXTRACTOR_STAGE_NAME = 'ExtractTFJSPredictions'

_MODELS_SUBDIR = 'Models'
_EXAMPLES_SUBDIR = 'Input_Examples'
_OUTPUTS_SUBDIR = 'Inference_Results'

_MODEL_JSON = 'model.json'
_DATA_JSON = 'data.json'
_DTYPE_JSON = 'dtype.json'
_SHAPE_JSON = 'shape.json'
_TF_INPUT_NAME_JSON = 'tf_input_name.json'


# TODO(b/149981535) Determine if we should merge with RunInference.
@beam.typehints.with_input_types(beam.typehints.List[types.Extracts])
@beam.typehints.with_output_types(types.Extracts)
class _TFJSPredictionDoFn(model_util.BatchReducibleDoFnWithModels):
  """A DoFn that loads tfjs models and predicts."""

  def __init__(self, eval_config: config.EvalConfig,
               eval_shared_models: Dict[Text, types.EvalSharedModel]) -> None:
    super(_TFJSPredictionDoFn, self).__init__(
        {k: v.model_loader for k, v in eval_shared_models.items()})
    self._eval_config = eval_config
    self._src_model_paths = {
        k: v.model_path for k, v in eval_shared_models.items()
    }

  def setup(self):
    super(_TFJSPredictionDoFn, self).setup()
    self._binary_path = get_tfjs_binary()

    base_path = tempfile.mkdtemp()
    base_model_path = os.path.join(base_path, _MODELS_SUBDIR)

    self._model_properties = {}
    for model_name, model_path in self._src_model_paths.items():
      with tf.io.gfile.GFile(os.path.join(model_path, _MODEL_JSON)) as f:
        model_json = json.load(f)
        if ('userDefinedMetadata' in model_json and
            'signature' in model_json['userDefinedMetadata']):
          model_signature = model_json['userDefinedMetadata']['signature']
        else:
          model_signature = model_json['signature']
        model_inputs = {}
        for k, v in model_signature['inputs'].items():
          model_inputs[k] = [int(i['size']) for i in v['tensorShape']['dim']]

        model_outputs = {}
        for k, v in model_signature['outputs'].items():
          model_outputs[k] = [int(i['size']) for i in v['tensorShape']['dim']]

      cur_model_path = os.path.join(base_model_path, model_name)
      self._model_properties[model_name] = {
          'inputs': model_inputs,
          'outputs': model_outputs,
          'path': cur_model_path
      }

      # We copy models to local tmp storage so that the tfjs binary can
      # access them.
      tf.io.gfile.makedirs(cur_model_path)
      for directory, _, files in tf.io.gfile.walk(model_path):
        cur_path = os.path.join(cur_model_path,
                                os.path.relpath(directory, model_path))
        tf.io.gfile.makedirs(cur_path)
        for f in files:
          src_path = os.path.join(directory, f)
          tf.io.gfile.copy(src_path, os.path.join(cur_path, f))

  def _batch_reducible_process(
      self, elements: List[types.Extracts]) -> Sequence[types.Extracts]:
{'fraction_non_alphanumeric': 0.09134964865519749, 'fraction_numerical': 0.004361521686455052, 'mean_word_length': 3.984903381642512, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4671119', 'n_tokens_mistral': 2599, 'n_tokens_neox': 2559, 'n_words': 682}