





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       __A					(					enum.Enum				):

			'''simple docstring'''







			lowerCAmelCase_							  =		0
			lowerCAmelCase_							  =		1
			lowerCAmelCase_							  =		2






@add_end_docstrings(lowerCAmelCase				)
class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		"""
    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 ,						*__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







				super().__init__(*__lowerCAmelCase ,						**__lowerCAmelCase							)
				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=__lowerCAmelCase ,						**self._forward_params							)
						lowerCamelCase__              =	{**self._preprocess_params, **preprocess_params}
						lowerCamelCase__              =	{**self._forward_params, **forward_params}





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						**__lowerCAmelCase ,						):



				'''simple docstring'''







				lowerCamelCase__              =	{}
				if prefix is not None:
					lowerCamelCase__              =	prefix
				if prefix:
					lowerCamelCase__              =	self.tokenizer(
					    __lowerCAmelCase ,						padding=__lowerCAmelCase ,						add_special_tokens=__lowerCAmelCase ,						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(__lowerCAmelCase							)
				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(__lowerCAmelCase ,						add_special_tokens=__lowerCAmelCase							)
					if len(__lowerCAmelCase							) > 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 	__lowerCamelCase       (					self ,						*__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







				if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
					kwargs.update({'''add_space_before_punct_symbol''': True}							)

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





			def __call__(					self ,						__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







				return super().__call__(__lowerCAmelCase ,						**__lowerCAmelCase							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase ,						__lowerCAmelCase="" ,						__lowerCAmelCase=None ,						**__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	self.tokenizer(
				    prefix + prompt_text ,						padding=__lowerCAmelCase ,						add_special_tokens=__lowerCAmelCase ,						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 	__lowerCamelCase       (					self ,						__lowerCAmelCase ,						**__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	model_inputs['''input_ids''']
				lowerCamelCase__              =	model_inputs.get('''attention_mask''' ,						__lowerCAmelCase							)
				# 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=__lowerCAmelCase ,						attention_mask=__lowerCAmelCase ,						**__lowerCAmelCase							)
				lowerCamelCase__              =	generated_sequence.shape[0]
				if self.framework == "pt":
					lowerCamelCase__              =	generated_sequence.reshape(__lowerCAmelCase ,						out_b // in_b ,						*generated_sequence.shape[1:]							)
				elif self.framework == "tf":
					lowerCamelCase__              =	tf.reshape(__lowerCAmelCase ,						(in_b, out_b // in_b, *generated_sequence.shape[1:])							)
				return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase ,						__lowerCAmelCase=ReturnType.FULL_TEXT ,						__lowerCAmelCase=True							):



				'''simple docstring'''







				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(
						    __lowerCAmelCase ,						skip_special_tokens=__lowerCAmelCase ,						clean_up_tokenization_spaces=__lowerCAmelCase ,						)

						# 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=__lowerCAmelCase ,						clean_up_tokenization_spaces=__lowerCAmelCase ,						)							)

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

						lowerCamelCase__              =	{'''generated_text''': all_text}
					records.append(__lowerCAmelCase							)

				return records










# Usage:
# ./gen-card-allenai-wmt16.py

import os
from pathlib import Path





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case							)       ->   Any:







	'''simple docstring'''







	lowerCamelCase__              =	{
	    '''en''': '''Machine learning is great, isn\'t it?''',
	    '''ru''': '''Машинное обучение - это здорово, не так ли?''',
	    '''de''': '''Maschinelles Lernen ist großartig, nicht wahr?''',
	}

	# BLUE scores as follows:
	# "pair": [fairseq, transformers]
	lowerCamelCase__              =	{
	    '''wmt16-en-de-dist-12-1''': [2_8.3, 2_7.5_2],
	    '''wmt16-en-de-dist-6-1''': [2_7.4, 2_7.1_1],
	    '''wmt16-en-de-12-1''': [2_6.9, 2_5.7_5],
	}
	lowerCamelCase__              =	F'{src_lang}-{tgt_lang}'

	lowerCamelCase__              =	F'\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "allenai/{model_name}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel   | fairseq | transformers\n-------|---------|----------\n{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n    year={{2020}},\n    eprint={{2006.10369}},\n    archivePrefix={{arXiv}},\n    primaryClass={{cs.CL}}\n}}\n```\n\n'
	model_card_dir.mkdir(parents=__snake_case ,exist_ok=__snake_case							)
	lowerCamelCase__              =	os.path.join(__snake_case ,'''README.md'''							)
	print(F'Generating {path}'							)
	with open(__snake_case ,'''w''' ,encoding='''utf-8'''							) as f:
		f.write(__snake_case							)


# make sure we are under the root of the project
_a						=   Path(__file__).resolve().parent.parent.parent
_a						=   repo_dir / "model_cards"

for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]:
			_a						=   model_cards_dir / "allenai" / model_name
			write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)



