
import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
			import tensorflow as tf





class       _lowerCAmelCase   (      enum.Enum			):
				_lowercase     						=0
				_lowercase     						=1
				_lowercase     						=2





@add_end_docstrings(__a			)
class       _lowerCAmelCase   (      __a			):
				_lowercase     						='''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''




				def __init__(   self							,							*_UpperCamelCase							,							**_UpperCamelCase	)							-> Optional[int]:
							super().__init__(*_UpperCamelCase							,							**_UpperCamelCase	)
							self.check_model_type(
							    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING	)
							if "prefix" not in self._preprocess_params:
										# This is very specific. The logic is quite complex and needs to be done
										# as a "default".
										# It also defines both some preprocess_kwargs and generate_kwargs
										# which is why we cannot put them in their respective methods.
										lowerCAmelCase_         =      None
										if self.model.config.prefix is not None:
													lowerCAmelCase_         =      self.model.config.prefix
										if prefix is None and self.model.__class__.__name__ in [
										    "XLNetLMHeadModel",
										    "TransfoXLLMHeadModel",
										    "TFXLNetLMHeadModel",
										    "TFTransfoXLLMHeadModel",
										]:
													# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
													lowerCAmelCase_         =      self.XL_PREFIX
										if prefix is not None:
													# Recalculate some generate_kwargs linked to prefix.
													lowerCAmelCase_      ,    lowerCAmelCase_      ,    lowerCAmelCase_         =      self._sanitize_parameters(prefix=_UpperCamelCase							,							**self._forward_params	)
													lowerCAmelCase_         =      {**self._preprocess_params, **preprocess_params}
													lowerCAmelCase_         =      {**self._forward_params, **forward_params}




				def 	__a		(   self							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							_UpperCamelCase=None							,							**_UpperCamelCase							,							)							-> List[Any]:
							lowerCAmelCase_         =      {}
							if prefix is not None:
										lowerCAmelCase_         =      prefix
							if prefix:
										lowerCAmelCase_         =      self.tokenizer(
										    _UpperCamelCase							,							padding=_UpperCamelCase							,							add_special_tokens=_UpperCamelCase							,							return_tensors=self.framework	)
										lowerCAmelCase_         =      prefix_inputs["input_ids"].shape[-1]

							if handle_long_generation is not None:
										if handle_long_generation not in {"hole"}:
													raise ValueError(
													    f"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
													    " [None, 'hole']"	)
										lowerCAmelCase_         =      handle_long_generation

							preprocess_params.update(_UpperCamelCase	)
							lowerCAmelCase_         =      generate_kwargs

							lowerCAmelCase_         =      {}
							if return_full_text is not None and return_type is None:
										if return_text is not None:
													raise ValueError("`return_text` is mutually exclusive with `return_full_text`"	)
										if return_tensors is not None:
													raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`"	)
										lowerCAmelCase_         =      ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
							if return_tensors is not None and return_type is None:
										if return_text is not None:
													raise ValueError("`return_text` is mutually exclusive with `return_tensors`"	)
										lowerCAmelCase_         =      ReturnType.TENSORS
							if return_type is not None:
										lowerCAmelCase_         =      return_type
							if clean_up_tokenization_spaces is not None:
										lowerCAmelCase_         =      clean_up_tokenization_spaces

							if stop_sequence is not None:
										lowerCAmelCase_         =      self.tokenizer.encode(_UpperCamelCase							,							add_special_tokens=_UpperCamelCase	)
										if len(_UpperCamelCase	) > 1:
													warnings.warn(
													    "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
													    " the stop sequence will be used as the stop sequence string in the interim."	)
										lowerCAmelCase_         =      stop_sequence_ids[0]

							return preprocess_params, forward_params, postprocess_params




				def 	__a		(   self							,							*_UpperCamelCase							,							**_UpperCamelCase	)							-> Any:
							# Parse arguments
							if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
										kwargs.update({"add_space_before_punct_symbol": True}	)

							return super()._parse_and_tokenize(*_UpperCamelCase							,							**_UpperCamelCase	)




				def __call__(   self							,							_UpperCamelCase							,							**_UpperCamelCase	)							-> Optional[int]:
							return super().__call__(_UpperCamelCase							,							**_UpperCamelCase	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase=""							,							_UpperCamelCase=None							,							**_UpperCamelCase	)							-> str:
							lowerCAmelCase_         =      self.tokenizer(
							    prefix + prompt_text							,							padding=_UpperCamelCase							,							add_special_tokens=_UpperCamelCase							,							return_tensors=self.framework	)
							lowerCAmelCase_         =      prompt_text

							if handle_long_generation == "hole":
										lowerCAmelCase_         =      inputs["input_ids"].shape[-1]
										if "max_new_tokens" in generate_kwargs:
													lowerCAmelCase_         =      generate_kwargs["max_new_tokens"]
										else:
													lowerCAmelCase_         =      generate_kwargs.get("max_length"							,							self.model.config.max_length	) - cur_len
													if new_tokens < 0:
																raise ValueError("We cannot infer how many new tokens are expected"	)
										if cur_len + new_tokens > self.tokenizer.model_max_length:
													lowerCAmelCase_         =      self.tokenizer.model_max_length - new_tokens
													if keep_length <= 0:
																raise ValueError(
																    "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
																    " models max length"	)

													lowerCAmelCase_         =      inputs["input_ids"][:, -keep_length:]
													if "attention_mask" in inputs:
																lowerCAmelCase_         =      inputs["attention_mask"][:, -keep_length:]

							return inputs




				def 	__a		(   self							,							_UpperCamelCase							,							**_UpperCamelCase	)							-> Any:
							lowerCAmelCase_         =      model_inputs["input_ids"]
							lowerCAmelCase_         =      model_inputs.get("attention_mask"							,							_UpperCamelCase	)
							# Allow empty prompts
							if input_ids.shape[1] == 0:
										lowerCAmelCase_         =      None
										lowerCAmelCase_         =      None
										lowerCAmelCase_         =      1
							else:
										lowerCAmelCase_         =      input_ids.shape[0]
							lowerCAmelCase_         =      model_inputs.pop("prompt_text"	)

							# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
							# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
							lowerCAmelCase_         =      generate_kwargs.pop("prefix_length"							,							0	)
							if prefix_length > 0:
										lowerCAmelCase_         =      "max_new_tokens" in generate_kwargs or (
										    "generation_config" in generate_kwargs
										    and generate_kwargs["generation_config"].max_new_tokens is not None
										)
										if not has_max_new_tokens:
													lowerCAmelCase_         =      generate_kwargs.get("max_length"	) or self.model.config.max_length
													generate_kwargs["max_length"] += prefix_length
										lowerCAmelCase_         =      "min_new_tokens" in generate_kwargs or (
										    "generation_config" in generate_kwargs
										    and generate_kwargs["generation_config"].min_new_tokens is not None
										)
										if not has_min_new_tokens and "min_length" in generate_kwargs:
													generate_kwargs["min_length"] += prefix_length

        # BS x SL
							lowerCAmelCase_         =      self.model.generate(input_ids=_UpperCamelCase							,							attention_mask=_UpperCamelCase							,							**_UpperCamelCase	)
							lowerCAmelCase_         =      generated_sequence.shape[0]
							if self.framework == "pt":
										lowerCAmelCase_         =      generated_sequence.reshape(_UpperCamelCase							,							out_b // in_b							,							*generated_sequence.shape[1:]	)
							elif self.framework == "tf":
										lowerCAmelCase_         =      tf.reshape(_UpperCamelCase							,							(in_b, out_b // in_b, *generated_sequence.shape[1:])	)
							return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase=ReturnType.FULL_TEXT							,							_UpperCamelCase=True	)							-> str:
							lowerCAmelCase_         =      model_outputs["generated_sequence"][0]
							lowerCAmelCase_         =      model_outputs["input_ids"]
							lowerCAmelCase_         =      model_outputs["prompt_text"]
							lowerCAmelCase_         =      generated_sequence.numpy().tolist()
							lowerCAmelCase_         =      []
							for sequence in generated_sequence:
										if return_type == ReturnType.TENSORS:
													lowerCAmelCase_         =      {"generated_token_ids": sequence}
										elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
													# Decode text
													lowerCAmelCase_         =      self.tokenizer.decode(
													    _UpperCamelCase							,							skip_special_tokens=_UpperCamelCase							,							clean_up_tokenization_spaces=_UpperCamelCase							,							)

													# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
													if input_ids is None:
																lowerCAmelCase_         =      0
													else:
																lowerCAmelCase_         =      len(
																    self.tokenizer.decode(
																        input_ids[0]							,							skip_special_tokens=_UpperCamelCase							,							clean_up_tokenization_spaces=_UpperCamelCase							,							)	)

													if return_type == ReturnType.FULL_TEXT:
																lowerCAmelCase_         =      prompt_text + text[prompt_length:]
													else:
																lowerCAmelCase_         =      text[prompt_length:]

													lowerCAmelCase_         =      {"generated_text": all_text}
										records.append(_UpperCamelCase	)

							return records





# Note: if you intend to run this script make sure you look under scripts/fsmt/
# to locate the appropriate script to do the work correctly. There is a set of scripts to:
# - download and prepare data and run the conversion script
# - perform eval to get the best hparam into the config
# - generate model_cards - useful if you have multiple models from the same paper

import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname

import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary

from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging


logging.set_verbosity_warning()

_A  =	2

# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
_A  =	{
    # fairseq:
    "wmt19-ru-en": {"length_penalty": 1.1},
    "wmt19-en-ru": {"length_penalty": 1.15},
    "wmt19-en-de": {"length_penalty": 1.0},
    "wmt19-de-en": {"length_penalty": 1.1},
    # allenai:
    "wmt16-en-de-dist-12-1": {"length_penalty": 0.6},
    "wmt16-en-de-dist-6-1": {"length_penalty": 0.6},
    "wmt16-en-de-12-1": {"length_penalty": 0.8},
    "wmt19-de-en-6-6-base": {"length_penalty": 0.6},
    "wmt19-de-en-6-6-big": {"length_penalty": 0.6},
}

# this remaps the different models to their organization names
_A  =	{}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
			_A  =	"facebook"
for m in [
    "wmt16-en-de-dist-12-1",
    "wmt16-en-de-dist-6-1",
    "wmt16-en-de-12-1",
    "wmt19-de-en-6-6-base",
    "wmt19-de-en-6-6-big",
]:
			_A  =	"allenai"






def   lowerCamelCase__							(							__lowerCAmelCase    :    Dict							):




			"""simple docstring"""


			lowerCAmelCase_         =      dict((re.sub(r"@@$"       ,				""       ,				__lowerCAmelCase							), v) if k.endswith("@@"							) else (re.sub(r"$"       ,				"</w>"       ,				__lowerCAmelCase							), v) for k, v in d.items()							)
			lowerCAmelCase_         =      "<s> <pad> </s> <unk>".split()
			# restore the special tokens
			for k in keep_keys:
						del da[F"""{k}</w>"""]
						lowerCAmelCase_         =      d[k]  # restore
			return da






def   lowerCamelCase__							(							__lowerCAmelCase    :    List[str]       ,				__lowerCAmelCase    :    Optional[Any]							):




			"""simple docstring"""


			assert os.path.exists(__lowerCAmelCase							)
			os.makedirs(__lowerCAmelCase       ,				exist_ok=__lowerCAmelCase							)
			print(F"""Writing results to {pytorch_dump_folder_path}"""							)

			# handle various types of models

			lowerCAmelCase_         =      basename(__lowerCAmelCase							)
			lowerCAmelCase_         =      dirname(__lowerCAmelCase							)

			lowerCAmelCase_         =      fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
			lowerCAmelCase_         =      cls.hub_models()
			lowerCAmelCase_         =      {"bpe": "fastbpe", "tokenizer": "moses"}
			lowerCAmelCase_         =      "."
			# note: since the model dump is old, fairseq has upgraded its model some
			# time later, and it does a whole lot of rewrites and splits on the saved
			# weights, therefore we can't use torch.load() directly on the model file.
			# see: upgrade_state_dict(state_dict) in fairseq_model.py
			print(F"""using checkpoint {checkpoint_file}"""							)
			lowerCAmelCase_         =      hub_utils.from_pretrained(
			    __lowerCAmelCase       ,				__lowerCAmelCase       ,				__lowerCAmelCase       ,				archive_map=__lowerCAmelCase       ,				**__lowerCAmelCase							)

			lowerCAmelCase_         =      vars(chkpt["args"]["model"]							)

			lowerCAmelCase_         =      args["source_lang"]
			lowerCAmelCase_         =      args["target_lang"]

			lowerCAmelCase_         =      dirname(__lowerCAmelCase							)
			lowerCAmelCase_         =      basename(__lowerCAmelCase							)

			# dicts
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				F"""dict.{src_lang}.txt"""							)
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				F"""dict.{tgt_lang}.txt"""							)

			lowerCAmelCase_         =      Dictionary.load(__lowerCAmelCase							)
			lowerCAmelCase_         =      rewrite_dict_keys(src_dict.indices							)
			lowerCAmelCase_         =      len(__lowerCAmelCase							)
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				"vocab-src.json"							)
			print(F"""Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records"""							)
			with open(__lowerCAmelCase       ,				"w"       ,				encoding="utf-8"							) as f:
						f.write(json.dumps(__lowerCAmelCase       ,				ensure_ascii=__lowerCAmelCase       ,				indent=__lowerCAmelCase							)							)

			# detect whether this is a do_lower_case situation, which can be derived by checking whether we
			# have at least one uppercase letter in the source vocab
			lowerCAmelCase_         =      True
			for k in src_vocab.keys():
						if not k.islower():
									lowerCAmelCase_         =      False
									break

			lowerCAmelCase_         =      Dictionary.load(__lowerCAmelCase							)
			lowerCAmelCase_         =      rewrite_dict_keys(tgt_dict.indices							)
			lowerCAmelCase_         =      len(__lowerCAmelCase							)
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				"vocab-tgt.json"							)
			print(F"""Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records"""							)
			with open(__lowerCAmelCase       ,				"w"       ,				encoding="utf-8"							) as f:
						f.write(json.dumps(__lowerCAmelCase       ,				ensure_ascii=__lowerCAmelCase       ,				indent=__lowerCAmelCase							)							)

			# merges_file (bpecodes)
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				VOCAB_FILES_NAMES["merges_file"]							)
			for fn in ["bpecodes", "code"]:  # older fairseq called the merges file "code"
						lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				__lowerCAmelCase							)
						if os.path.exists(__lowerCAmelCase							):
									break
			with open(__lowerCAmelCase       ,				encoding="utf-8"							) as fin:
						lowerCAmelCase_         =      fin.read()
			lowerCAmelCase_         =      re.sub(r" \d+$"       ,				""       ,				__lowerCAmelCase       ,				0       ,				re.M							)  # remove frequency number
			print(F"""Generating {merges_file}"""							)
			with open(__lowerCAmelCase       ,				"w"       ,				encoding="utf-8"							) as fout:
						fout.write(__lowerCAmelCase							)

			# model config
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				"config.json"							)

			# validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
			# may have to modify the tokenizer if a different type is used by a future model
			assert args["bpe"] == "fastbpe", F"""need to extend tokenizer to support bpe={args['bpe']}"""
			assert args["tokenizer"] == "moses", F"""need to extend tokenizer to support bpe={args['tokenizer']}"""

			lowerCAmelCase_         =      {
			    "architectures": ["FSMTForConditionalGeneration"],
			    "model_type": "fsmt",
			    "activation_dropout": args["activation_dropout"],
			    "activation_function": "relu",
			    "attention_dropout": args["attention_dropout"],
			    "d_model": args["decoder_embed_dim"],
			    "dropout": args["dropout"],
			    "init_std": 0.02,
			    "max_position_embeddings": args["max_source_positions"],
			    "num_hidden_layers": args["encoder_layers"],
			    "src_vocab_size": src_vocab_size,
			    "tgt_vocab_size": tgt_vocab_size,
			    "langs": [src_lang, tgt_lang],
			    "encoder_attention_heads": args["encoder_attention_heads"],
			    "encoder_ffn_dim": args["encoder_ffn_embed_dim"],
			    "encoder_layerdrop": args["encoder_layerdrop"],
			    "encoder_layers": args["encoder_layers"],
			    "decoder_attention_heads": args["decoder_attention_heads"],
			    "decoder_ffn_dim": args["decoder_ffn_embed_dim"],
			    "decoder_layerdrop": args["decoder_layerdrop"],
			    "decoder_layers": args["decoder_layers"],
			    "bos_token_id": 0,
			    "pad_token_id": 1,
			    "eos_token_id": 2,
			    "is_encoder_decoder": True,
			    "scale_embedding": not args["no_scale_embedding"],
			    "tie_word_embeddings": args["share_all_embeddings"],
			}

			# good hparam defaults to start with
			lowerCAmelCase_         =      5
			lowerCAmelCase_         =      False
			if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
						lowerCAmelCase_         =      best_score_hparams[model_dir]["length_penalty"]
			else:
						lowerCAmelCase_         =      1.0

			print(F"""Generating {fsmt_model_config_file}"""							)
			with open(__lowerCAmelCase       ,				"w"       ,				encoding="utf-8"							) as f:
						f.write(json.dumps(__lowerCAmelCase       ,				ensure_ascii=__lowerCAmelCase       ,				indent=__lowerCAmelCase							)							)

			# tokenizer config
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				__lowerCAmelCase							)

			lowerCAmelCase_         =      {
			    "langs": [src_lang, tgt_lang],
			    "model_max_length": 1024,
			    "do_lower_case": do_lower_case,
			}

			print(F"""Generating {fsmt_tokenizer_config_file}"""							)
			with open(__lowerCAmelCase       ,				"w"       ,				encoding="utf-8"							) as f:
						f.write(json.dumps(__lowerCAmelCase       ,				ensure_ascii=__lowerCAmelCase       ,				indent=__lowerCAmelCase							)							)

			# model
			lowerCAmelCase_         =      chkpt["models"][0]
			lowerCAmelCase_         =      model.state_dict()

			# rename keys to start with 'model.'
			lowerCAmelCase_         =      OrderedDict(("model." + k, v) for k, v in model_state_dict.items()							)

			# remove unneeded keys
			lowerCAmelCase_         =      [
			    "model.model",
			    "model.encoder.version",
			    "model.decoder.version",
			    "model.encoder_embed_tokens.weight",
			    "model.decoder_embed_tokens.weight",
			    "model.encoder.embed_positions._float_tensor",
			    "model.decoder.embed_positions._float_tensor",
			]
			for k in ignore_keys:
						model_state_dict.pop(__lowerCAmelCase       ,				__lowerCAmelCase							)

			lowerCAmelCase_         =      FSMTConfig.from_pretrained(__lowerCAmelCase							)
			lowerCAmelCase_         =      FSMTForConditionalGeneration(__lowerCAmelCase							)

			# check that it loads ok
			model_new.load_state_dict(__lowerCAmelCase       ,				strict=__lowerCAmelCase							)

			# save
			lowerCAmelCase_         =      os.path.join(__lowerCAmelCase       ,				__lowerCAmelCase							)
			print(F"""Generating {pytorch_weights_dump_path}"""							)
			torch.save(__lowerCAmelCase       ,				__lowerCAmelCase							)

			print("Conversion is done!"							)
			print("\nLast step is to upload the files to s3"							)
			print(F"""cd {data_root}"""							)
			print(F"""transformers-cli upload {model_dir}"""							)


if __name__ == "__main__":
			_A  =	argparse.ArgumentParser()
			# Required parameters
			parser.add_argument(
			    "--fsmt_checkpoint_path",
			    default=None,
			    type=str,
			    required=True,
			    help=(
			        "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,"
			        " bpecodes, etc."
			    ),
			)
			parser.add_argument(
			    "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
			)
			_A  =	parser.parse_args()
			convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)



