
"""simple docstring"""
import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


SCREAMING_SNAKE_CASE_					     =	NewType('''DataClass''', Any)
SCREAMING_SNAKE_CASE_					     =	NewType('''DataClassType''', Any)

def  lowercase     (_lowerCAmelCase						):
						if isinstance(_lowerCAmelCase ,    _lowerCAmelCase						):
												return v
						if v.lower() in ("yes", "true", "t", "y", "1"):
												return True
						elif v.lower() in ("no", "false", "f", "n", "0"):
												return False
						else:
												raise ArgumentTypeError(
												    f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."""						)

def  lowercase     (_lowerCAmelCase						):
						__lowerCAmelCase     =  {str(_lowerCAmelCase						): choice for choice in choices}
						return lambda _lowerCAmelCase						: str_to_choice.get(_lowerCAmelCase ,    _lowerCAmelCase						)

def  lowercase     (*,
    _lowerCAmelCase = None ,    _lowerCAmelCase = None ,    _lowerCAmelCase = dataclasses.MISSING ,    _lowerCAmelCase = dataclasses.MISSING ,    _lowerCAmelCase = None ,    **_lowerCAmelCase ,    ):
						if metadata is None:
												# Important, don't use as default param in function signature because dict is mutable and shared across function calls
												__lowerCAmelCase     =  {}
						if aliases is not None:
												__lowerCAmelCase     =  aliases
						if help is not None:
												__lowerCAmelCase     =  help

						return dataclasses.field(metadata=_lowerCAmelCase ,    default=_lowerCAmelCase ,    default_factory=_lowerCAmelCase ,    **_lowerCAmelCase						)



class       lowerCAmelCase_		(				A__ ):



							'''simple docstring'''





							_snake_case						      =		42




							def __init__( self    ,				snake_case_    ,				**snake_case_				)       ->  int:
													# To make the default appear when using --help
													if "formatter_class" not in kwargs:
																			__lowerCAmelCase     =  ArgumentDefaultsHelpFormatter
													super().__init__(**snake_case_				)
													if dataclasses.is_dataclass(snake_case_				):
																			__lowerCAmelCase     =  [dataclass_types]
													__lowerCAmelCase     =  list(snake_case_				)
													for dtype in self.dataclass_types:
																			self._add_dataclass_arguments(snake_case_				)




							@staticmethod
							def    A__						( snake_case_    ,				snake_case_				)       ->  Tuple:
													__lowerCAmelCase     =  f"""--{field.name}"""
													__lowerCAmelCase     =  field.metadata.copy()
													# field.metadata is not used at all by Data Classes,
													# it is provided as a third-party extension mechanism.
													if isinstance(field.type    ,				snake_case_				):
																			raise RuntimeError(
																			    """Unresolved type detected, which should have been done with the help of """
																			    """`typing.get_type_hints` method by default"""				)

													__lowerCAmelCase     =  kwargs.pop("""aliases"""    ,				[]				)
													if isinstance(snake_case_    ,				snake_case_				):
																			__lowerCAmelCase     =  [aliases]

													__lowerCAmelCase     =  getattr(field.type    ,				"""__origin__"""    ,				field.type				)
													if origin_type is Union or (hasattr(snake_case_    ,				"""UnionType"""				) and isinstance(snake_case_    ,				types.UnionType				)):
																			if str not in field.type.__args__ and (
																			    len(field.type.__args__				) != 2 or type(snake_case_				) not in field.type.__args__
																			):
																									raise ValueError(
																									    """Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"""
																									    """ the argument parser only supports one type per argument."""
																									    f""" Problem encountered in field '{field.name}'."""				)
																			if type(snake_case_				) not in field.type.__args__:
																									# filter `str` in Union
																									__lowerCAmelCase     =  field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
																									__lowerCAmelCase     =  getattr(field.type    ,				"""__origin__"""    ,				field.type				)
																			elif bool not in field.type.__args__:
																									# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
																									__lowerCAmelCase     =  (
																									    field.type.__args__[0] if isinstance(snake_case_    ,				field.type.__args__[1]				) else field.type.__args__[1]
																									)
																									__lowerCAmelCase     =  getattr(field.type    ,				"""__origin__"""    ,				field.type				)

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
													__lowerCAmelCase     =  {}
													if origin_type is Literal or (isinstance(field.type    ,				snake_case_				) and issubclass(field.type    ,				snake_case_				)):
																			if origin_type is Literal:
																									__lowerCAmelCase     =  field.type.__args__
																			else:
																									__lowerCAmelCase     =  [x.value for x in field.type]

																			__lowerCAmelCase     =  make_choice_type_function(kwargs["""choices"""]				)

																			if field.default is not dataclasses.MISSING:
																									__lowerCAmelCase     =  field.default
																			else:
																									__lowerCAmelCase     =  True
													elif field.type is bool or field.type == Optional[bool]:
																			# Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
																			# We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
																			__lowerCAmelCase     =  copy(snake_case_				)

																			# Hack because type=bool in argparse does not behave as we want.
																			__lowerCAmelCase     =  string_to_bool
																			if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
																									# Default value is False if we have no default when of type bool.
																									__lowerCAmelCase     =  False if field.default is dataclasses.MISSING else field.default
																									# This is the value that will get picked if we don't include --field_name in any way
																									__lowerCAmelCase     =  default
																									# This tells argparse we accept 0 or 1 value after --field_name
																									__lowerCAmelCase     =  """?"""
																									# This is the value that will get picked if we do --field_name (without value)
																									__lowerCAmelCase     =  True
													elif isclass(snake_case_				) and issubclass(snake_case_    ,				snake_case_				):
																			__lowerCAmelCase     =  field.type.__args__[0]
																			__lowerCAmelCase     =  """+"""
																			if field.default_factory is not dataclasses.MISSING:
																									__lowerCAmelCase     =  field.default_factory()
																			elif field.default is dataclasses.MISSING:
																									__lowerCAmelCase     =  True
													else:
																			__lowerCAmelCase     =  field.type
																			if field.default is not dataclasses.MISSING:
																									__lowerCAmelCase     =  field.default
																			elif field.default_factory is not dataclasses.MISSING:
																									__lowerCAmelCase     =  field.default_factory()
																			else:
																									__lowerCAmelCase     =  True
													parser.add_argument(snake_case_    ,				*snake_case_    ,				**snake_case_				)

													# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
													# Order is important for arguments with the same destination!
													# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
													# here and we do not need those changes/additional keys.
													if field.default is True and (field.type is bool or field.type == Optional[bool]):
																			__lowerCAmelCase     =  False
																			parser.add_argument(f"""--no_{field.name}"""    ,				action="""store_false"""    ,				dest=field.name    ,				**snake_case_				)




							def    A__						( self    ,				snake_case_				)       ->  Optional[Any]:
													if hasattr(snake_case_    ,				"""_argument_group_name"""				):
																			__lowerCAmelCase     =  self.add_argument_group(dtype._argument_group_name				)
													else:
																			__lowerCAmelCase     =  self

													try:
																			__lowerCAmelCase     =  get_type_hints(snake_case_				)
													except NameError:
																			raise RuntimeError(
																			    f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
																			    """removing line of `from __future__ import annotations` which opts in Postponed """
																			    """Evaluation of Annotations (PEP 563)"""				)
													except TypeError as ex:
																			# Remove this block when we drop Python 3.9 support
																			if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(snake_case_				):
																									__lowerCAmelCase     =  """.""".join(map(snake_case_    ,				sys.version_info[:3]				)				)
																									raise RuntimeError(
																									    f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
																									    """line of `from __future__ import annotations` which opts in union types as """
																									    """`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To """
																									    """support Python versions that lower than 3.10, you need to use """
																									    """`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of """
																									    """`X | None`."""				) from ex
																			raise

													for field in dataclasses.fields(snake_case_				):
																			if not field.init:
																									continue
																			__lowerCAmelCase     =  type_hints[field.name]
																			self._parse_dataclass_field(snake_case_    ,				snake_case_				)




							def    A__						( self    ,				snake_case_=None    ,				snake_case_=False    ,				snake_case_=True    ,				snake_case_=None    ,				snake_case_=None    ,				)       ->  Tuple[DataClass, ...]:

													if args_file_flag or args_filename or (look_for_args_file and len(sys.argv				)):
																			__lowerCAmelCase     =  []

																			if args_filename:
																									args_files.append(Path(snake_case_				)				)
																			elif look_for_args_file and len(sys.argv				):
																									args_files.append(Path(sys.argv[0]				).with_suffix(""".args"""				)				)

																			# args files specified via command line flag should overwrite default args files so we add them last
																			if args_file_flag:
																									# Create special parser just to extract the args_file_flag values
																									__lowerCAmelCase     =  ArgumentParser()
																									args_file_parser.add_argument(snake_case_    ,				type=snake_case_    ,				action="""append"""				)

																									# Use only remaining args for further parsing (remove the args_file_flag)
																									__lowerCAmelCase   ,     __lowerCAmelCase     =  args_file_parser.parse_known_args(args=snake_case_				)
																									__lowerCAmelCase     =  vars(snake_case_				).get(args_file_flag.lstrip("""-"""				)    ,				snake_case_				)

																									if cmd_args_file_paths:
																															args_files.extend([Path(snake_case_				) for p in cmd_args_file_paths]				)

																			__lowerCAmelCase     =  []
																			for args_file in args_files:
																									if args_file.exists():
																															file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
																			__lowerCAmelCase     =  file_args + args if args is not None else file_args + sys.argv[1:]
													__lowerCAmelCase   ,     __lowerCAmelCase     =  self.parse_known_args(args=snake_case_				)
													__lowerCAmelCase     =  []
													for dtype in self.dataclass_types:
																			__lowerCAmelCase     =  {f.name for f in dataclasses.fields(snake_case_				) if f.init}
																			__lowerCAmelCase     =  {k: v for k, v in vars(snake_case_				).items() if k in keys}
																			for k in keys:
																									delattr(snake_case_    ,				snake_case_				)
																			__lowerCAmelCase     =  dtype(**snake_case_				)
																			outputs.append(snake_case_				)
													if len(namespace.__dict__				) > 0:
																			# additional namespace.
																			outputs.append(snake_case_				)
													if return_remaining_strings:
																			return (*outputs, remaining_args)
													else:
																			if remaining_args:
																									raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}"""				)

																			return (*outputs,)




							def    A__						( self    ,				snake_case_    ,				snake_case_ = False				)       ->  Tuple[DataClass, ...]:
													__lowerCAmelCase     =  set(args.keys()				)
													__lowerCAmelCase     =  []
													for dtype in self.dataclass_types:
																			__lowerCAmelCase     =  {f.name for f in dataclasses.fields(snake_case_				) if f.init}
																			__lowerCAmelCase     =  {k: v for k, v in args.items() if k in keys}
																			unused_keys.difference_update(inputs.keys()				)
																			__lowerCAmelCase     =  dtype(**snake_case_				)
																			outputs.append(snake_case_				)
													if not allow_extra_keys and unused_keys:
																			raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(snake_case_				)}"""				)
													return tuple(snake_case_				)




							def    A__						( self    ,				snake_case_    ,				snake_case_ = False				)       ->  Tuple[DataClass, ...]:
													with open(Path(snake_case_				)    ,				encoding="""utf-8"""				) as open_json_file:
																			__lowerCAmelCase     =  json.loads(open_json_file.read()				)
													__lowerCAmelCase     =  self.parse_dict(snake_case_    ,				allow_extra_keys=snake_case_				)
													return tuple(snake_case_				)




							def    A__						( self    ,				snake_case_    ,				snake_case_ = False				)       ->  Tuple[DataClass, ...]:
													__lowerCAmelCase     =  self.parse_dict(yaml.safe_load(Path(snake_case_				).read_text()				)    ,				allow_extra_keys=snake_case_				)
													return tuple(snake_case_				)


"""simple docstring"""
# Usage:
# ./gen-card-allenai-wmt16.py

import os
from pathlib import Path

def  lowercase     (_lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase						):
						__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""": [28.3, 27.52],
						    """wmt16-en-de-dist-6-1""": [27.4, 27.11],
						    """wmt16-en-de-12-1""": [26.9, 25.75],
						}
						__lowerCAmelCase     =  f"""{src_lang}-{tgt_lang}"""

						__lowerCAmelCase     =  f"""
---
language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt16
- allenai
license: apache-2.0
datasets:
- wmt16
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of fairseq-based [wmt16 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).

All 3 models are available:

* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)
* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)
* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)


## 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   | fairseq | transformers
-------|---------|----------
{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}

The 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.

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 wmt16 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt16 -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/wmt16/)
- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)


### 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=_lowerCAmelCase ,    exist_ok=_lowerCAmelCase						)
						__lowerCAmelCase     =  os.path.join(_lowerCAmelCase ,    """README.md"""						)
						print(f"""Generating {path}"""						)
						with open(_lowerCAmelCase ,    """w""" ,    encoding="""utf-8"""						) as f:
												f.write(_lowerCAmelCase						)


# make sure we are under the root of the project
SCREAMING_SNAKE_CASE_					     =	Path(__file__).resolve().parent.parent.parent
SCREAMING_SNAKE_CASE_					     =	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"]:
			SCREAMING_SNAKE_CASE_					     =	model_cards_dir / '''allenai''' / model_name
			write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
