# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.

# Lint as: python3
"""Object for relabeling."""
# pylint: disable=unused-variable
# pylint: disable=undefined-variable
# pylint: disable=wildcard-import

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow.compat.v2 as tf

from hal.labeler.labeler_utils import *


class Labeler:
  """A object that approximates the oracle.

  Attributes:
    generated_label_num: number of lables generated per transition
    max_sequence_length: maximum length of sequence generated
    temperature: temperature of sampling
    encoder: encoder of the captioning model
    decoder: decoder of the captioning model
    answering_encoder: encoder of the answering model
    answering_decoder: decoder of the answering model
    answering_projection_layer: final projection layer of the answering model
  """

  def __init__(self, labeler_config, name='labeler'):
    """Initializes the labeler.

    Args:
      labeler_config: configuration of the labeler
      name: optional name
    """
    self._name = name
    self.generated_label_num = labeler_config['generated_label_num']
    self.max_sequence_length = labeler_config['max_sequence_length']
    self.temperature = labeler_config['sampling_temperature']

  def set_captioning_model(self, labeler_config, saved_weight_path=None):
    """Set up the captinong model and maybe load weights.

    Args:
      labeler_config: configuration of the labeler
      saved_weight_path: optional path where weights are loaded from
    """
    self.encoder = get_captioning_encoder(labeler_config['captioning_encoder'])
    self.decoder = get_captioning_decoder(labeler_config['captioning_decoder'])
    if saved_weight_path:
      ckpt = tf.train.Checkpoint(encoder=self.encoder, decoder=self.decoder)
      latest = tf.train.latest_checkpoint(saved_weight_path)
      assert latest, 'Captioning model ckpt not found in {}.'.format(
          saved_weight_path)
      print('Loading captioning model from: {}'.format(latest))
      ckpt.restore(latest)

  def set_answering_model(self, labeler_config, saved_weight_path=None):
    """Set up and load models of the answering model and maybe load weights.

    Args:
      labeler_config: configuration of the labeler
      saved_weight_path: optional path where weights are loaded from
    """
    self.answering_encoder = get_answering_encoder(
        labeler_config['answering_encoder'])
    self.answering_decoder = get_answering_decoder(
        labeler_config['answering_decoder'])
    self.answering_projection_layer = tf.keras.layers.Dense(
        1, activation='sigmoid', name='answering_projection')
    if saved_weight_path:
      ckpt = tf.train.Checkpoint(
          encoder=self.answering_encoder,
          decoder=self.answering_decoder,
          projection_layer=self.answering_projection_layer)
      latest = tf.train.latest_checkpoint(saved_weight_path)
      assert latest, 'Answering model ckpt not found in {}.'.format(
          saved_weight_path)
      print('Loading answering model from: {}'.format(latest))
      ckpt.restore(latest)

  def label_trajectory(self, trajectory, null_token=None):
    """Generate valid instructions for a trajectory of transitions.

    Args:
      trajectory: configuration of the labeler