# Copyright 2020 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
#
#      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.
"""ScaNN index evaluator custom component."""

import os
import time
from typing import Any, Dict, List, Optional, Text, Union
import logging
import json

import tfx
from tfx.types import standard_artifacts
from tfx.types.component_spec import ChannelParameter
from tfx.types.component_spec import ExecutionParameter
from tfx.dsl.components.base import base_executor
from tfx.dsl.components.base import base_component
from tfx.dsl.components.base import executor_spec
from tfx.types import artifact_utils
from tfx.utils import io_utils
from typing import Optional
from tfx import types

import tensorflow as tf
import numpy as np
import tensorflow_data_validation as tfdv
from tensorflow_transform.tf_metadata import schema_utils

try:
  from . import item_matcher
  from . import scann_indexer
except:
  import item_matcher
  import scann_indexer

  
QUERIES_SAMPLE_RATIO = 0.01
MAX_NUM_QUERIES = 10000
NUM_NEIGBHOURS = 20


class IndexEvaluatorSpec(tfx.types.ComponentSpec):
  
  INPUTS = {
    'examples': ChannelParameter(type=standard_artifacts.Examples),
    'schema': ChannelParameter(type=standard_artifacts.Schema),
    'model': ChannelParameter(type=standard_artifacts.Model),
  }
    
  OUTPUTS = {
    'evaluation': ChannelParameter(type=standard_artifacts.ModelEvaluation),
    'blessing': ChannelParameter(type=standard_artifacts.ModelBlessing),
  }
    
  PARAMETERS = {
    'min_recall': ExecutionParameter(type=float),
    'max_latency': ExecutionParameter(type=float),
  }


class ScaNNIndexEvaluatorExecutor(base_executor.BaseExecutor):
  
  def Do(self, 
         input_dict: Dict[Text, List[types.Artifact]],
         output_dict: Dict[Text, List[types.Artifact]],
         exec_properties: Dict[Text, Any]) -> None:
    
    if 'examples' not in input_dict:
      raise ValueError('Examples is missing from input dict.')
    if 'model' not in input_dict:
      raise ValueError('Model is missing from input dict.')
    if 'evaluation' not in output_dict:
      raise ValueError('Evaluation is missing from output dict.')
    if 'blessing' not in output_dict:
      raise ValueError('Blessing is missing from output dict.')
    
    valid = True
        
    self._log_startup(input_dict, output_dict, exec_properties)
    
    embedding_files_pattern = io_utils.all_files_pattern(
      artifact_utils.get_split_uri(input_dict['examples'], 'train'))
    
    schema_file_path = artifact_utils.get_single_instance(
      input_dict['schema']).uri + '/schema.pbtxt'
    
    vocabulary, embeddings = scann_indexer.load_embeddings(
      embedding_files_pattern, schema_file_path)
    
    num_embeddings = embeddings.shape[0]
    logging.info(f'{num_embeddings} embeddings are loaded.')
    num_queries = int(min(num_embeddings * QUERIES_SAMPLE_RATIO, MAX_NUM_QUERIES))
    logging.info(f'Sampling {num_queries} query embeddings for evaluation...')
    query_embedding_indices = np.random.choice(num_embeddings, num_queries)
    query_embeddings = np.take(embeddings, query_embedding_indices, axis=0)

    # Load Exact matcher
    exact_matcher = item_matcher.ExactMatcher(embeddings, vocabulary)
    exact_matches = []
    logging.info(f'Computing exact matches for the queries...')
    for query in query_embeddings:
      exact_matches.append(exact_matcher.match(query, NUM_NEIGBHOURS))
    logging.info(f'Exact matches are computed.')