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

import json

import tensorflow as tf
import numpy as np

from DLT2T.utils import trainer_utils as utils
from DLT2T.visualization import attention

%%javascript
require.config({
  paths: {
      d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min'
  }
});

"""
Explanation: Create Your Own Visualizations!
Instructions:
1. Install DLT2T and train up a Transformer model following the instruction in the repository https://github.com/tensorflow/DLT2T.
2. Update cell 3 to point to your checkpoint, it is currently set up to read from the default checkpoint location that would be created from following the instructions above.
3. If you used custom hyper parameters then update cell 4.
4. Run the notebook!
End of explanation
"""


import os
# PUT THE MODEL YOU WANT TO LOAD HERE!

PROBLEM = 'translate_ende_wmt32k'
MODEL = 'transformer'
HPARAMS = 'transformer_base_single_gpu'

DATA_DIR=os.path.expanduser('~/t2t_data')
TRAIN_DIR=os.path.expanduser('~/t2t_train/%s/%s-%s' % (PROBLEM, MODEL, HPARAMS))
print(TRAIN_DIR)

FLAGS = tf.flags.FLAGS
FLAGS.problems = PROBLEM
FLAGS.hparams_set = HPARAMS
FLAGS.data_dir = DATA_DIR
FLAGS.model = MODEL

hparams = utils.create_hparams(HPARAMS, PROBLEM, DATA_DIR)

# SET EXTRA HYPER PARAMS HERE!
# e.g.
# hparams.batch_size = 1024

num_datashards = utils.devices.data_parallelism().n

input_fn = utils.input_fn_builder.build_input_fn(
    mode=tf.estimator.ModeKeys.EVAL,
    hparams=hparams,
    data_dir=DATA_DIR,
    num_datashards=num_datashards)

inputs, target = input_fn()
features = inputs
features['targets'] = target

def encode(string):
    subtokenizer = hparams.problems[0].vocabulary['inputs']
    return [subtokenizer.encode(string) + [1] + [0]]

def decode(ids):
    return hparams.problems[0].vocabulary['targets'].decode(np.squeeze(ids))

def to_tokens(ids):
    ids = np.squeeze(ids)
    subtokenizer = hparams.problems[0].vocabulary['targets']
    tokens = []
    for _id in ids:
        if _id == 0:
            tokens.append('<PAD>')
        elif _id == 1:
            tokens.append('<EOS>')
        else:
            tokens.append(subtokenizer._subtoken_id_to_subtoken_string(_id))
    return tokens

"""
Explanation: Data
End of explanation
"""


spec = utils.model_builder.model_fn(MODEL, features, tf.estimator.ModeKeys.EVAL, hparams, problem_names=[PROBLEM])
predictions_dict = spec.predictions

with tf.variable_scope(tf.get_variable_scope(), reuse=True):
    spec = utils.model_builder.model_fn(MODEL, features, tf.estimator.ModeKeys.PREDICT, hparams, problem_names=[PROBLEM])
    beam_out = spec.predictions['outputs']

"""
Explanation: Model
End of explanation
"""


sv = tf.train.Supervisor(
    logdir=TRAIN_DIR,
    global_step=tf.Variable(0, dtype=tf.int64, trainable=False, name='global_step'))
sess = sv.PrepareSession(config=tf.ConfigProto(allow_soft_placement=True))
sv.StartQueueRunners(
    sess,
    tf.get_default_graph().get_collection(tf.GraphKeys.QUEUE_RUNNERS))

"""
Explanation: Session
End of explanation
"""


# Get the attention tensors from the graph.
# This need to be done using the training graph since the inference uses a tf.while_loop
# and you cant fetch tensors from inside a while_loop.

enc_atts = []
dec_atts = []
encdec_atts = []

for i in range(hparams.num_hidden_layers):
    enc_att = tf.get_default_graph().get_operation_by_name(
        "body/model/parallel_0/body/encoder/layer_%i/self_attention/multihead_attention/dot_product_attention/attention_weights" % i).values()[0]
    dec_att = tf.get_default_graph().get_operation_by_name(
        "body/model/parallel_0/body/decoder/layer_%i/self_attention/multihead_attention/dot_product_attention/attention_weights" % i).values()[0]
    encdec_att = tf.get_default_graph().get_operation_by_name(
        "body/model/parallel_0/body/decoder/layer_%i/encdec_attention/multihead_attention/dot_product_attention/attention_weights" % i).values()[0]

    enc_atts.append(enc_att)
    dec_atts.append(dec_att)
    encdec_atts.append(encdec_att)

"""
Explanation: Visualization
End of explanation
"""


inp, out, logits = sess.run([inputs['inputs'], target, predictions_dict['predictions']])

print("Input:    ", decode(inp[0]))
print("Gold:     ", decode(out[0]))
logits = np.squeeze(logits[0])
tokens = np.argmax(logits, axis=1)
print("Gold out: ", decode(tokens))

"""
Explanation: Test translation from the dataset
End of explanation
"""


eng = "I have three dogs."

inp_ids = encode(eng)
beam_decode = sess.run(beam_out, {
    inputs['inputs']: np.expand_dims(np.expand_dims(inp_ids, axis=2), axis=3),
})
trans = decode(beam_decode[0])
print(trans)

output_ids = beam_decode

# Get attentions
np_enc_atts, np_dec_atts, np_encdec_atts = sess.run([enc_atts, dec_atts, encdec_atts], {
    inputs['inputs']: np.expand_dims(np.expand_dims(inp_ids, axis=2), axis=3),
    target: np.expand_dims(np.expand_dims(output_ids, axis=2), axis=3),
})

%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
    return false;
}

"""
Explanation: Visualize Custom Sentence
End of explanation
"""


inp_text = to_tokens(inp_ids)
out_text = to_tokens(output_ids)

attention.show(inp_text, out_text, np_enc_atts, np_dec_atts, np_encdec_atts)

"""
Explanation: Interpreting the Visualizations

The layers drop down allow you to view the different Transformer layers, 0-indexed of course.
Tip: The first layer, last layer and 2nd to last layer are usually the most interpretable.
The attention dropdown allows you to select different pairs of encoder-decoder attentions:
All: Shows all types of attentions together. NOTE: There is no relation between heads of the same color - between the decoder self attention and decoder-encoder attention since they do not share parameters.
Input - Input: Shows only the encoder self-attention.
Input - Output: Shows the decoder’s attention on the encoder. NOTE: Every decoder layer attends to the final layer of encoder so the visualization will show the attention on the final encoder layer regardless of what layer is selected in the drop down.
Output - Output: Shows only the decoder self-attention. NOTE: The visualization might be slightly misleading in the first layer since the text shown is the target of the decoder, the input to the decoder at layer 0 is this text with a GO symbol prepreded.
The colored squares represent the different attention heads.
You can hide or show a given head by clicking on it’s color.
Double clicking a color will hide all other colors, double clicking on a color when it’s the only head showing will show all the heads again.
You can hover over a word to see the individual attention weights for just that position.
Hovering over the words on the left will show what that position attended to.
Hovering over the words on the right will show what positions attended to it.
End of explanation
"""


