# Copyright 2021 Zilliz. 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.

import numpy
import os
import torch
import shutil
from pathlib import Path
from typing import Union

from transformers import AutoTokenizer, AutoModel, AutoModelForMaskedLM, AutoModelForCausalLM

from towhee.operator import NNOperator
from towhee import register
# from towhee.dc2 import accelerate

import warnings
import logging
from transformers import logging as t_logging

from .train_mlm_with_hf_trainer import train_mlm_with_hf_trainer
from .train_clm_with_hf_trainer import train_clm_with_hf_trainer

log = logging.getLogger('run_op')
warnings.filterwarnings('ignore')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
t_logging.set_verbosity_error()


# @accelerate
class Model:
    def __init__(self, model_name, device, checkpoint_path):
        try:
            self.model = AutoModel.from_pretrained(model_name).to(device)
            if hasattr(self.model, 'pooler') and self.model.pooler:
                self.model.pooler = None
        except Exception as e:
            log.error(f"Fail to load model by name: {self.model_name}")
            raise e
        if checkpoint_path:
            try:
                state_dict = torch.load(checkpoint_path, map_location=device)
                self.model.load_state_dict(state_dict)
            except Exception as e:
                log.error(f"Fail to load state dict from {checkpoint_path}: {e}")
        self.model.eval()

    def __call__(self, *args, **kwargs):
        outs = self.model(*args, **kwargs, return_dict=True)
        return outs['last_hidden_state']


@register(output_schema=['vec'])
class AutoTransformers(NNOperator):
    """
    NLP embedding operator that uses the pretrained transformers model gathered by huggingface.
    Args:
        model_name (`str`):
            The model name to load a pretrained model from transformers.
        checkpoint_path (`str`):
            The local checkpoint path.
        tokenizer (`object`):
            The tokenizer to tokenize input text as model inputs.
    """

    def __init__(self,
                 model_name: str = None,
                 checkpoint_path: str = None,
                 tokenizer: object = None,
                 device: str = None,
                 return_sentence_emb: bool = True
                 ):
        super().__init__()
        if device is None:
            device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.device = device
        self.model_name = model_name
        self.return_sentence_emb = return_sentence_emb

        if self.model_name:
            model_list = self.supported_model_names()
            assert model_name in model_list, f"Invalid model name: {model_name}. Supported model names: {model_list}"
            self.model = Model(
                model_name=self.model_name, device=self.device, checkpoint_path=checkpoint_path)
            if tokenizer is None:
                try:
                    self.tokenizer = AutoTokenizer.from_pretrained(model_name)
                except Exception as e:
                    log.error(f'Fail to load default tokenizer by name: {self.model_name}')
                    raise e
            else:
                self.tokenizer = tokenizer
            if not self.tokenizer.pad_token:
                self.tokenizer.pad_token = '[PAD]'
        else:
            log.warning('The operator is initialized without specified model.')
            pass

    def __call__(self, data: Union[str, list]) -> numpy.ndarray:
        if isinstance(data, str):
            txt = [data]
        else:
            txt = data
        try:
            inputs = self.tokenizer(txt, padding=True, truncation=True, return_tensors="pt").to(self.device)
        except Exception as e:
            log.error(f'Fail to tokenize inputs: {e}')
            raise e
        try:
            outs = self.model(**inputs)
        except Exception as e:
            log.error(f'Invalid input for the model: {self.model_name}')
            raise e
        if self.return_sentence_emb:
            outs = self.post_proc(outs, inputs)
        features = outs.cpu().detach().numpy()
        if isinstance(data, str):
            features = features.squeeze(0)
        else:
            features = list(features)
        return features

    @property
    def _model(self):
        return self.model.model

    def post_proc(self, token_embeddings, inputs):
        token_embeddings = token_embeddings.to(self.device)
        attention_mask = inputs['attention_mask'].to(self.device)
        input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
        sentence_embs = torch.sum(
            token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
        return sentence_embs

    def save_model(self, model_type: str = 'pytorch', output_file: str = 'default'):
        if output_file == 'default':
            output_file = str(Path(__file__).parent)
            output_file = os.path.join(output_file, 'saved', model_type)
            os.makedirs(output_file, exist_ok=True)
            name = self.model_name.replace('/', '-')
            output_file = os.path.join(output_file, name)
            if model_type in ['pytorch', 'torchscript']:
                output_file = output_file + '.pt'
            elif model_type == 'onnx':
                output_file = output_file + '.onnx'
            else:
                raise AttributeError('Unsupported model_type.')

        dummy_input = '[CLS]'
        inputs = self.tokenizer(dummy_input, padding=True, truncation=True, return_tensors='pt')  # a dictionary
        if model_type == 'pytorch':
            torch.save(self._model, output_file)
        elif model_type == 'torchscript':
            inputs = list(inputs.values())
            try:
                try:
                    jit_model = torch.jit.script(self._model)
                except Exception:
                    jit_model = torch.jit.trace(self._model, inputs, strict=False)
                torch.jit.save(jit_model, output_file)
            except Exception as e:
                log.error(f'Fail to save as torchscript: {e}.')
                raise RuntimeError(f'Fail to save as torchscript: {e}.')
        elif model_type == 'onnx':
            from transformers.onnx.features import FeaturesManager
            from transformers.onnx import export
            model_kind, model_onnx_config = FeaturesManager.check_supported_model_or_raise(
                self._model, feature='default')
            onnx_config = model_onnx_config(self._model.config)
            # if os.path.isdir(output_file[:-5]):
            #     shutil.rmtree(output_file[:-5])
            # print('********', Path(output_file))
            onnx_inputs, onnx_outputs = export(
                self.tokenizer,
                self._model,
                config=onnx_config,
                opset=13,
                output=Path(output_file)
            )
        # todo: elif format == 'tensorrt':
        else:
            log.error(f'Unsupported format "{format}".')
        return Path(output_file).resolve()

    @property
    def supported_formats(self):
        onnxes = self.supported_model_names(format='onnx')
        if self.model_name in onnxes:
            return ['onnx']
        else:
            return ['pytorch']

    @staticmethod
    def supported_model_names(format: str = None):
        full_list = [
            "bert-large-uncased",
            "bert-base-cased",
            "bert-base-uncased",
            "bert-large-cased",
            "bert-base-multilingual-uncased",
            "bert-base-multilingual-cased",
            "bert-base-chinese",
            "bert-base-german-cased",
            "bert-large-uncased-whole-word-masking",
            "bert-large-cased-whole-word-masking",
            "bert-large-uncased-whole-word-masking-finetuned-squad",
            "bert-large-cased-whole-word-masking-finetuned-squad",
            "bert-base-cased-finetuned-mrpc",
            "bert-base-german-dbmdz-cased",
            "bert-base-german-dbmdz-uncased",
            "cl-tohoku/bert-base-japanese-whole-word-masking",
            "cl-tohoku/bert-base-japanese-char",
            "cl-tohoku/bert-base-japanese-char-whole-word-masking",
            "TurkuNLP/bert-base-finnish-cased-v1",
            "TurkuNLP/bert-base-finnish-uncased-v1",
            "wietsedv/bert-base-dutch-cased",
            "google/bigbird-roberta-base",
            "google/bigbird-roberta-large",
            "google/bigbird-base-trivia-itc",
            "albert-base-v1",
            "albert-large-v1",
            "albert-xlarge-v1",
            "albert-xxlarge-v1",
            "albert-base-v2",
            "albert-large-v2",
            "albert-xlarge-v2",
            "albert-xxlarge-v2",
            "facebook/bart-large",
            "google/bert_for_seq_generation_L-24_bbc_encoder",
            "google/bigbird-pegasus-large-arxiv",
            "google/bigbird-pegasus-large-pubmed",
            "google/bigbird-pegasus-large-bigpatent",
            "google/canine-s",
            "google/canine-c",
            "YituTech/conv-bert-base",
            "YituTech/conv-bert-medium-small",
            "YituTech/conv-bert-small",
            "ctrl",
            "microsoft/deberta-base",
            "microsoft/deberta-large",
            "microsoft/deberta-xlarge",
            "microsoft/deberta-base-mnli",
            "microsoft/deberta-large-mnli",
            "microsoft/deberta-xlarge-mnli",
            "distilbert-base-uncased",
            "distilbert-base-uncased-distilled-squad",
            "distilbert-base-cased",
            "distilbert-base-cased-distilled-squad",
            "distilbert-base-german-cased",
            "distilbert-base-multilingual-cased",
            "distilbert-base-uncased-finetuned-sst-2-english",
            "google/electra-small-generator",
            "google/electra-base-generator",
            "google/electra-large-generator",
            "google/electra-small-discriminator",
            "google/electra-base-discriminator",
            "google/electra-large-discriminator",
            "google/fnet-base",
            "google/fnet-large",
            "facebook/wmt19-ru-en",
            "funnel-transformer/small",
            "funnel-transformer/small-base",
            "funnel-transformer/medium",
            "funnel-transformer/medium-base",
            "funnel-transformer/intermediate",
            "funnel-transformer/intermediate-base",
            "funnel-transformer/large",
            "funnel-transformer/large-base",
            "funnel-transformer/xlarge-base",
            "funnel-transformer/xlarge",
            "gpt2",
            "gpt2-medium",
            "gpt2-large",
            "gpt2-xl",
            "distilgpt2",
            "EleutherAI/gpt-neo-1.3B",
            "EleutherAI/gpt-j-6B",
            "kssteven/ibert-roberta-base",
            "allenai/led-base-16384",
            "google/mobilebert-uncased",
            "microsoft/mpnet-base",
            "uw-madison/nystromformer-512",
            "openai-gpt",
            "google/reformer-crime-and-punishment",
            "tau/splinter-base",
            "tau/splinter-base-qass",
            "tau/splinter-large",
            "tau/splinter-large-qass",
            "squeezebert/squeezebert-uncased",
            "squeezebert/squeezebert-mnli",
            "squeezebert/squeezebert-mnli-headless",
            "transfo-xl-wt103",
            "xlm-mlm-en-2048",
            "xlm-mlm-ende-1024",
            "xlm-mlm-enfr-1024",
            "xlm-mlm-enro-1024",
            "xlm-mlm-tlm-xnli15-1024",
            "xlm-mlm-xnli15-1024",
            "xlm-clm-enfr-1024",
            "xlm-clm-ende-1024",
            "xlm-mlm-17-1280",
            "xlm-mlm-100-1280",
            "xlm-roberta-base",
            "xlm-roberta-large",
            "xlm-roberta-large-finetuned-conll02-dutch",
            "xlm-roberta-large-finetuned-conll02-spanish",
            "xlm-roberta-large-finetuned-conll03-english",
            "xlm-roberta-large-finetuned-conll03-german",
            "xlnet-base-cased",
            "xlnet-large-cased",
            "uw-madison/yoso-4096",
            "microsoft/deberta-v2-xlarge",
            "microsoft/deberta-v2-xxlarge",
            "microsoft/deberta-v2-xlarge-mnli",
            "microsoft/deberta-v2-xxlarge-mnli",
            "flaubert/flaubert_small_cased",
            "flaubert/flaubert_base_uncased",
            "flaubert/flaubert_base_cased",
            "flaubert/flaubert_large_cased",
            "camembert-base",
            "Musixmatch/umberto-commoncrawl-cased-v1",
            "Musixmatch/umberto-wikipedia-uncased-v1",
        ]
        full_list.sort()
        if format is None:
            model_list = full_list
        elif format == 'pytorch':
            to_remove = []
            assert set(to_remove).issubset(set(full_list))
            model_list = list(set(full_list) - set(to_remove))
        elif format == 'torchscript':
            to_remove = [
                'EleutherAI/gpt-j-6B',
                'EleutherAI/gpt-neo-1.3B',
                'allenai/led-base-16384',
                'ctrl',
                'distilgpt2',
                'facebook/bart-large',
                'google/bigbird-pegasus-large-arxiv',
                'google/bigbird-pegasus-large-bigpatent',
                'google/bigbird-pegasus-large-pubmed',
                'google/canine-c',
                'google/canine-s',
                'google/reformer-crime-and-punishment',
                'gpt2',
                'gpt2-large',
                'gpt2-medium',
                'gpt2-xl',
                'microsoft/deberta-base',
                'microsoft/deberta-base-mnli',
                'microsoft/deberta-large',
                'microsoft/deberta-large-mnli',
                'microsoft/deberta-xlarge',
                'microsoft/deberta-xlarge-mnli',
                'openai-gpt',
                'transfo-xl-wt103',
                'uw-madison/yoso-4096',
                'xlm-clm-ende-1024',
                'xlm-clm-enfr-1024',
                'xlm-mlm-100-1280',
                'xlm-mlm-17-1280',
                'xlm-mlm-en-2048',
                'xlm-mlm-ende-1024',
                'xlm-mlm-enfr-1024',
                'xlm-mlm-enro-1024',
                'xlm-mlm-tlm-xnli15-1024',
                'xlm-mlm-xnli15-1024',
                'xlnet-base-cased',
                'xlnet-large-cased',
                'microsoft/deberta-v2-xlarge',
                'microsoft/deberta-v2-xxlarge',
                'microsoft/deberta-v2-xlarge-mnli',
                'microsoft/deberta-v2-xxlarge-mnli',
                'flaubert/flaubert_small_cased',
                'flaubert/flaubert_base_uncased',
                'flaubert/flaubert_base_cased',
                'flaubert/flaubert_large_cased'
            ]
            assert set(to_remove).issubset(set(full_list))
            model_list = list(set(full_list) - set(to_remove))
        elif format == 'onnx':
            to_remove = [
                'ctrl',
                'funnel-transformer/intermediate',
                'funnel-transformer/large',
                'funnel-transformer/medium',
                'funnel-transformer/small',
                'funnel-transformer/xlarge',
                'google/canine-c',
                'google/canine-s',
                'google/fnet-base',
                'google/fnet-large',
                'google/reformer-crime-and-punishment',
                'transfo-xl-wt103',
                'uw-madison/yoso-4096',
                'xlnet-base-cased',
                'xlnet-large-cased'
            ]
            assert set(to_remove).issubset(set(full_list))
            model_list = list(set(full_list) - set(to_remove))
        # todo: elif format == 'tensorrt':
        else:
            log.error(f'Invalid format "{format}". Currently supported formats: "pytorch", "torchscript".')
        return model_list

    def train(self, training_config=None,
              train_dataset=None,
              eval_dataset=None,
              resume_checkpoint_path=None, **kwargs):
        task = kwargs.pop('task', None)
        data_args = kwargs.pop('data_args', None)
        training_args = kwargs.pop('training_args', None)
        prepare_model_weights_f = kwargs.pop('prepare_model_weights_f', None)

        if task == 'mlm' or task is None:
            model_with_head = AutoModelForMaskedLM.from_pretrained(self.model_name)
            if prepare_model_weights_f is not None:
                model_with_head = prepare_model_weights_f(self._model, model_with_head, **kwargs)

            train_mlm_with_hf_trainer(
                model_with_head,
                self.tokenizer,
                data_args,
                training_args,
                **kwargs
            )
        elif task == 'clm':
            model_with_head = AutoModelForCausalLM.from_pretrained(self.model_name)
            if prepare_model_weights_f is not None:
                model_with_head = prepare_model_weights_f(self._model, model_with_head, **kwargs)

            train_clm_with_hf_trainer(
                model_with_head,
                self.tokenizer,
                data_args,
                training_args,
                **kwargs
            )