
"""simple docstring"""


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

import os
from pathlib import Path



def        _lowerCamelCase(__UpperCamelCase       ,					__UpperCamelCase       ,					__UpperCamelCase       ,					__UpperCamelCase			)							->					int:
	_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								={
	    """wmt19-de-en-6-6-base""": [0, 38.37],
	    """wmt19-de-en-6-6-big""": [0, 39.90],
	}
	_lowerCAmelCase								=F'''{src_lang}-{tgt_lang}'''

	_lowerCAmelCase								=F'''
---

language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- allenai
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of fairseq-based [wmt19 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.

For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).

2 models are available:

* [wmt19-de-en-6-6-big](https://huggingface.co/allenai/wmt19-de-en-6-6-big)
* [wmt19-de-en-6-6-base](https://huggingface.co/allenai/wmt19-de-en-6-6-base)


## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = "allenai/{model_name}"
tokenizer = FSMTTokenizer.from_pretrained(mname)
model = FSMTForConditionalGeneration.from_pretrained(mname)

input = "{texts[src_lang]}"
input_ids = tokenizer.encode(input, return_tensors="pt")
outputs = model.generate(input_ids)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded) # {texts[tgt_lang]}

```

#### Limitations and bias


## Training data

Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).

## Eval results

Here are the BLEU scores:

model   |  transformers
-------|---------
{model_name}  |  {scores[model_name][1]}

The score was calculated using this code:

```bash
git clone https://github.com/huggingface/transformers
cd transformers
export PAIR={pair}
export DATA_DIR=data/$PAIR
export SAVE_DIR=data/$PAIR
export BS=8
export NUM_BEAMS=5
mkdir -p $DATA_DIR
sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
echo $PAIR
PYTHONPATH="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
```

## Data Sources

- [training, etc.](http://www.statmt.org/wmt19/)
- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)


### BibTeX entry and citation info

```
@misc{{kasai2020deep,
    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},
    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},
    year={{2020}},
    eprint={{2006.10369}},
    archivePrefix={{arXiv}},
    primaryClass={{cs.CL}}
}}
```

'''
	model_card_dir.mkdir(parents=__UpperCamelCase       ,					exist_ok=__UpperCamelCase			)
	_lowerCAmelCase								=os.path.join(__UpperCamelCase       ,					"""README.md"""			)
	print(F'''Generating {path}'''			)
	with open(__UpperCamelCase       ,					"""w"""       ,					encoding="""utf-8"""			) as f:
		f.write(__UpperCamelCase			)


# 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 ["wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big"]:
			__A					=			model_cards_dir / 'allenai' / model_name
			write_model_card(model_card_dir, src_lang='de', tgt_lang='en', model_name=model_name)





"""simple docstring"""


import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


__A					=			logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
__A					=			direct_transformers_import(Path(__file__).parent)


__A					=			{
    'AutoTokenizer': 'PreTrainedTokenizerBase',
    'AutoFeatureExtractor': 'FeatureExtractionMixin',
    'AutoImageProcessor': 'ImageProcessingMixin',
}







class 						lowerCamelCase__   (   __magic_name__							):





			'''simple docstring'''
			lowerCamelCase       =						['''feature_extractor''', '''tokenizer''']
			# Names need to be attr_class for attr in attributes
			lowerCamelCase       =						None
			lowerCamelCase       =						None
			lowerCamelCase       =						None



			def __init__(				self	,	*__UpperCAmelCase	,	**__UpperCAmelCase    )					->	Dict:
				# Sanitize args and kwargs
				for key in kwargs:
					if key not in self.attributes:
						raise TypeError(f'''Unexpected keyword argument {key}.'''    )
				for arg, attribute_name in zip(__UpperCAmelCase	,	self.attributes    ):
					if attribute_name in kwargs:
						raise TypeError(f'''Got multiple values for argument {attribute_name}.'''    )
					else:
						_lowerCAmelCase								=arg

				if len(__UpperCAmelCase    ) != len(self.attributes    ):
					raise ValueError(
					    f'''This processor requires {len(self.attributes    )} arguments: {', '.join(self.attributes    )}. Got '''
					    f'''{len(__UpperCAmelCase    )} arguments instead.'''    )

				# Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
				for attribute_name, arg in kwargs.items():
					_lowerCAmelCase								=getattr(self	,	f'''{attribute_name}_class'''    )
					# Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
					_lowerCAmelCase								=AUTO_TO_BASE_CLASS_MAPPING.get(__UpperCAmelCase	,	__UpperCAmelCase    )
					if isinstance(__UpperCAmelCase	,	__UpperCAmelCase    ):
						_lowerCAmelCase								=tuple(getattr(__UpperCAmelCase	,	__UpperCAmelCase    ) for n in class_name if n is not None    )
					else:
						_lowerCAmelCase								=getattr(__UpperCAmelCase	,	__UpperCAmelCase    )

					if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase    ):
						raise ValueError(
						    f'''Received a {type(__UpperCAmelCase    ).__name__} for argument {attribute_name}, but a {class_name} was expected.'''    )

					setattr(self	,	__UpperCAmelCase	,	__UpperCAmelCase    )



			def __repr__(				self    )					->	Optional[int]:
				_lowerCAmelCase								=[f'''- {name}: {repr(getattr(self	,	__UpperCAmelCase    )    )}''' for name in self.attributes]
				_lowerCAmelCase								="""\n""".join(__UpperCAmelCase    )
				return f'''{self.__class__.__name__}:\n{attributes_repr}'''



			def    _lowerCAmelCase						(				self	,	__UpperCAmelCase	,	__UpperCAmelCase = False	,	**__UpperCAmelCase    )					->	Union[str, Any]:
				os.makedirs(__UpperCAmelCase	,	exist_ok=__UpperCAmelCase    )

				if push_to_hub:
					_lowerCAmelCase								=kwargs.pop("""commit_message"""	,	__UpperCAmelCase    )
					_lowerCAmelCase								=kwargs.pop("""repo_id"""	,	save_directory.split(os.path.sep    )[-1]    )
					_lowerCAmelCase								=self._create_repo(__UpperCAmelCase	,	**__UpperCAmelCase    )
					_lowerCAmelCase								=self._get_files_timestamps(__UpperCAmelCase    )
				# If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
				# loaded from the Hub.
				if self._auto_class is not None:
					_lowerCAmelCase								=[getattr(self	,	__UpperCAmelCase    ) for attribute_name in self.attributes]
					_lowerCAmelCase								=[(a.init_kwargs if isinstance(__UpperCAmelCase	,	__UpperCAmelCase    ) else a) for a in attrs]
					custom_object_save(self	,	__UpperCAmelCase	,	config=__UpperCAmelCase    )

				for attribute_name in self.attributes:
					_lowerCAmelCase								=getattr(self	,	__UpperCAmelCase    )
					# Include the processor class in the attribute config so this processor can then be reloaded with the
					# `AutoProcessor` API.
					if hasattr(__UpperCAmelCase	,	"""_set_processor_class"""    ):
						attribute._set_processor_class(self.__class__.__name__    )
					attribute.save_pretrained(__UpperCAmelCase    )

				if self._auto_class is not None:
					# We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
					for attribute_name in self.attributes:
						_lowerCAmelCase								=getattr(self	,	__UpperCAmelCase    )
						if isinstance(__UpperCAmelCase	,	__UpperCAmelCase    ):
							del attribute.init_kwargs["auto_map"]

				if push_to_hub:
					self._upload_modified_files(
					    __UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase	,	commit_message=__UpperCAmelCase	,	token=kwargs.get("""use_auth_token"""    )	,	)



			@classmethod
			def    _lowerCAmelCase						(				cls	,	__UpperCAmelCase	,	__UpperCAmelCase = None	,	__UpperCAmelCase = False	,	__UpperCAmelCase = False	,	__UpperCAmelCase = None	,	__UpperCAmelCase = "main"	,	**__UpperCAmelCase	,	)					->	Any:
				_lowerCAmelCase								=cache_dir
				_lowerCAmelCase								=force_download
				_lowerCAmelCase								=local_files_only
				_lowerCAmelCase								=revision

				_lowerCAmelCase								=kwargs.pop("""use_auth_token"""	,	__UpperCAmelCase    )
				if use_auth_token is not None:
					warnings.warn(
					    """The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers."""	,	__UpperCAmelCase    )
					if token is not None:
						raise ValueError(
						    """`token` and `use_auth_token` are both specified. Please set only the argument `token`."""    )
					_lowerCAmelCase								=use_auth_token

				if token is not None:
					# change to `token` in a follow-up PR
					_lowerCAmelCase								=token

				_lowerCAmelCase								=cls._get_arguments_from_pretrained(__UpperCAmelCase	,	**__UpperCAmelCase    )
				return cls(*__UpperCAmelCase    )



			@classmethod
			def    _lowerCAmelCase						(				cls	,	__UpperCAmelCase="AutoProcessor"    )					->	Optional[int]:
				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase    ):
					_lowerCAmelCase								=auto_class.__name__

				import transformers.models.auto as auto_module

				if not hasattr(__UpperCAmelCase	,	__UpperCAmelCase    ):
					raise ValueError(f'''{auto_class} is not a valid auto class.'''    )

				_lowerCAmelCase								=auto_class



			@classmethod
			def    _lowerCAmelCase						(				cls	,	__UpperCAmelCase	,	**__UpperCAmelCase    )					->	Optional[Any]:
				_lowerCAmelCase								=[]
				for attribute_name in cls.attributes:
					_lowerCAmelCase								=getattr(cls	,	f'''{attribute_name}_class'''    )
					if isinstance(__UpperCAmelCase	,	__UpperCAmelCase    ):
						_lowerCAmelCase								=tuple(getattr(__UpperCAmelCase	,	__UpperCAmelCase    ) if n is not None else None for n in class_name    )
						_lowerCAmelCase								=kwargs.get("""use_fast"""	,	__UpperCAmelCase    )
						if use_fast and classes[1] is not None:
							_lowerCAmelCase								=classes[1]
						else:
							_lowerCAmelCase								=classes[0]
					else:
						_lowerCAmelCase								=getattr(__UpperCAmelCase	,	__UpperCAmelCase    )

					args.append(attribute_class.from_pretrained(__UpperCAmelCase	,	**__UpperCAmelCase    )    )
				return args



			@property
			def    _lowerCAmelCase						(				self    )					->	Optional[int]:
				_lowerCAmelCase								=getattr(self	,	self.attributes[0]    )
				return getattr(__UpperCAmelCase	,	"""model_input_names"""	,	__UpperCAmelCase    )







__A					=			copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
			__A					=			ProcessorMixin.push_to_hub.__doc__.format(
			    object='processor', object_class='AutoProcessor', object_files='processor files'
			)



