code: # Copyright 2019 Google LLC. 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.
  """Tests for tfx.components.schema_gen.executor."""
  
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  
  import os
  import tensorflow as tf
  from tfx.components.schema_gen import executor
  from tfx.types import standard_artifacts
  from tfx.utils import io_utils
  
  
  class ExecutorTest(tf.test.TestCase):
  
    def setUp(self):
      super(ExecutorTest, self).setUp()
  
      self.source_data_dir = os.path.join(
          os.path.dirname(os.path.dirname(__file__)), 'testdata')
  
      self.train_stats_artifact = standard_artifacts.ExampleStatistics(
          split='train')
      self.train_stats_artifact.uri = os.path.join(self.source_data_dir,
                                                   'statistics_gen/train/')
  
      self.output_data_dir = os.path.join(
          os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()),
          self._testMethodName)
  
      self.schema_output = standard_artifacts.Schema()
      self.schema_output.uri = os.path.join(self.output_data_dir, 'schema_output')
  
      self.schema = standard_artifacts.Schema()
      self.schema.uri = os.path.join(self.source_data_dir, 'fixed_schema/')
  
      self.expected_schema = standard_artifacts.Schema()
      self.expected_schema.uri = os.path.join(self.source_data_dir, 'schema_gen/')
  
      self.input_dict = {
          'stats': [self.train_stats_artifact],
          'schema': None
      }
      self.output_dict = {
          'output': [self.schema_output],
      }
      self.exec_properties = {'infer_feature_shape': False}
  
    def _assertSchemaEqual(self, expected_schema, actual_schema):
      schema_reader = io_utils.SchemaReader()
      expected_schema_proto = schema_reader.read(
          os.path.join(expected_schema.uri, executor._DEFAULT_FILE_NAME))
      actual_schema_proto = schema_reader.read(
          os.path.join(actual_schema.uri, executor._DEFAULT_FILE_NAME))
      self.assertProtoEquals(expected_schema_proto, actual_schema_proto)
  
    def testDoWithStatistics(self):
      schema_gen_executor = executor.Executor()
      schema_gen_executor.Do(self.input_dict, self.output_dict,
                             self.exec_properties)
      self.assertNotEqual(0, len(tf.gfile.ListDirectory(self.schema_output.uri)))
      self._assertSchemaEqual(self.expected_schema, self.schema_output)
  
    def testDoWithSchema(self):
      self.input_dict['schema'] = [self.schema]
      self.input_dict.pop('stats')
      schema_gen_executor = executor.Executor()
      schema_gen_executor.Do(self.input_dict, self.output_dict,
                             self.exec_properties)
      self.assertNotEqual(0, len(tf.gfile.ListDirectory(self.schema_output.uri)))
      self._assertSchemaEqual(self.schema, self.schema_output)
  
    def testDoWithNonExistentSchema(self):
      non_existent_schema = standard_artifacts.Schema()
      non_existent_schema.uri = '/path/to/non_existent/schema'
  
      self.input_dict['schema'] = [non_existent_schema]
      self.input_dict.pop('stats')
  
      with self.assertRaises(ValueError):
        schema_gen_executor = executor.Executor()
        schema_gen_executor.Do(self.input_dict, self.output_dict,
                               self.exec_properties)
  
  
  if __name__ == '__main__':
    tf.test.main()
   # Copyright 2019 Google LLC. 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.
  """Iris flowers example using TFX."""
  
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  
  import os
  import tensorflow as tf
  from typing import Text
  from tfx.components.evaluator.component import Evaluator
  from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
  from tfx.components.example_validator.component import ExampleValidator
  from tfx.components.model_validator.component import ModelValidator
  from tfx.components.pusher.component import Pusher
  from tfx.components.schema_gen.component import SchemaGen
  from tfx.components.statistics_gen.component import StatisticsGen
  from tfx.components.trainer.component import Trainer
  from tfx.orchestration import metadata
  from tfx.orchestration import pipeline
  from tfx.orchestration.beam.beam_dag_runner import BeamDagRunner
  from tfx.proto import pusher_pb2
  from tfx.proto import trainer_pb2
  from tfx.utils.dsl_utils import external_input
  
  _pipeline_name = 'iris'
  
  # This example assumes that Iris flowers data is stored in ~/iris/data and the
  # utility function is in ~/iris. Feel free to customize as needed.
  _iris_root = os.path.join(os.environ['HOME'], 'iris')
  _data_root = os.path.join(_iris_root, 'data')
  # Python module file to inject customized logic into the TFX components. The
  # Transform and Trainer both require user-defined functions to run successfully.
  _module_file = os.path.join(_iris_root, 'iris_utils.py')
  # Path which can be listened to by the model server.  Pusher will output the
  # trained model here.
  _serving_model_dir = os.path.join(_iris_root, 'serving_model', _pipeline_name)
  
  # Directory and data locations.  This example assumes all of the flowers
  # example code and metadata library is relative to $HOME, but you can store
  # these files anywhere on your local filesystem.
  _tfx_root = os.path.join(os.environ['HOME'], 'tfx')
  _pipeline_root = os.path.join(_tfx_root, 'pipelines', _pipeline_name)
  # Sqlite ML-metadata db path.
  _metadata_path = os.path.join(_tfx_root, 'metadata', _pipeline_name,
                                'metadata.db')
  
  
  def _create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
                       module_file: Text, serving_model_dir: Text,
                       metadata_path: Text) -> pipeline.Pipeline:
    """Implements the Iris flowers pipeline with TFX."""
    examples = external_input(data_root)
  
    # Brings data into the pipeline or otherwise joins/converts training data.
    example_gen = CsvExampleGen(input=examples)
  
    # Computes statistics over data for visualization and example validation.
    statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])
  
    # Generates schema based on statistics files.
    infer_schema = SchemaGen(
        statistics=statistics_gen.outputs['statistics'], infer_feature_shape=True)
  
    # Performs anomaly detection based on statistics and data schema.
    validate_stats = ExampleValidator(
        statistics=statistics_gen.outputs['statistics'],
        schema=infer_schema.outputs['schema'])
  
    # Uses user-provided Python function that implements a model using TF-Learn.
    trainer = Trainer(
        module_file=module_file,
        examples=example_gen.outputs['examples'],
        schema=infer_schema.outputs['schema'],
        train_args=trainer_pb2.TrainArgs(num_steps=10000),
        eval_args=trainer_pb2.EvalArgs(num_steps=5000))
  
    # Uses TFMA to compute a evaluation statistics over features of a model.
    model_analyzer = Evaluator(
        examples=example_gen.outputs['examples'],
        model_exports=trainer.outputs['model'])
  
    # Performs quality validation of a candidate model (compared to a baseline).
    model_validator = ModelValidator(
        examples=example_gen.outputs['examples'], model=trainer.outputs['model'])
  
    # Checks whether the model passed the validation steps and pushes the model
    # to a file destination if check passed.
    pusher = Pusher(
        model=trainer.outputs['model'],
        model_blessing=model_validator.outputs['blessing'],
        push_destination=pusher_pb2.PushDestination(
            filesystem=pusher_pb2.PushDestination.Filesystem(
                base_directory=serving_model_dir)))
  
    return pipeline.Pipeline(
        pipeline_name=pipeline_name,
        pipeline_root=pipeline_root,
        components=[
            example_gen, statistics_gen, infer_schema, validate_stats, trainer,
            model_analyzer, model_validator, pusher
        ],
        enable_cache=True,
        metadata_connection_config=metadata.sqlite_metadata_connection_config(
            metadata_path),
        additional_pipeline_args={},
    )
  
  
  # To run this pipeline from the python CLI:
  #   $python iris_pipeline.py
  if __name__ == '__main__':
    tf.logging.set_verbosity(tf.logging.INFO)
    BeamDagRunner().run(
        _create_pipeline(
            pipeline_name=_pipeline_name,
            pipeline_root=_pipeline_root,
            data_root=_data_root,
            module_file=_module_file,
            serving_model_dir=_serving_model_dir,
            metadata_path=_metadata_path))
  
apis: tensorflow.gfile.ListDirectory tensorflow.test.main
apis: tensorflow.logging.set_verbosity