





'''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


snake_case_     =	NewType("""DataClass""", Any)
snake_case_     =	NewType("""DataClassType""", Any)
def 							_lowerCamelCase(  UpperCamelCase__    : List[str]		)		->  List[str]:
    if isinstance(UpperCamelCase__    ,       UpperCamelCase__		):
        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 							_lowerCamelCase(  UpperCamelCase__    : list		)		->  Callable[[str], Any]:
    A       :       Any							=						{str(UpperCamelCase__		): choice for choice in choices}
    return lambda UpperCamelCase__		: str_to_choice.get(UpperCamelCase__    ,       UpperCamelCase__		)
def 							_lowerCamelCase(  *,
    UpperCamelCase__    : Union[str, List[str]] = None    ,       UpperCamelCase__    : str = None    ,       UpperCamelCase__    : Any = dataclasses.MISSING    ,       UpperCamelCase__    : Callable[[], Any] = dataclasses.MISSING    ,       UpperCamelCase__    : dict = None    ,       **UpperCamelCase__    : Optional[int]    ,       )		->  dataclasses.Field:
    if metadata is None:
        # Important, don't use as default param in function signature because dict is mutable and shared across function calls
        A       :       Any							=						{}
    if aliases is not None:
        A       :       Optional[Any]							=						aliases
    if help is not None:
        A       :       Optional[int]							=						help

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





class   _lowercase						(							a				):
   _UpperCamelCase       		=   42


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


   @staticmethod
   def 					snake_case				( _UpperCAmelCase    ,   _UpperCAmelCase					):
       A       :       Any							=						f'''--{field.name}'''
       A       :       Any							=						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    ,   _UpperCAmelCase					):
           raise RuntimeError(
               '''Unresolved type detected, which should have been done with the help of '''
               '''`typing.get_type_hints` method by default'''					)

       A       :       Optional[Any]							=						kwargs.pop('''aliases'''    ,   []					)
       if isinstance(_UpperCAmelCase    ,   _UpperCAmelCase					):
           A       :       str							=						[aliases]

       A       :       Optional[Any]							=						getattr(field.type    ,   '''__origin__'''    ,   field.type					)
       if origin_type is Union or (hasattr(_UpperCAmelCase    ,   '''UnionType'''					) and isinstance(_UpperCAmelCase    ,   types.UnionType					)):
           if str not in field.type.__args__ and (
               len(field.type.__args__					) != 2 or type(_UpperCAmelCase					) 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(_UpperCAmelCase					) not in field.type.__args__:
               # filter `str` in Union
               A       :       Tuple							=						field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
               A       :       Optional[int]							=						getattr(field.type    ,   '''__origin__'''    ,   field.type					)
           elif bool not in field.type.__args__:
               # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
               A       :       str							=						(
                   field.type.__args__[0] if isinstance(_UpperCAmelCase    ,   field.type.__args__[1]					) else field.type.__args__[1]
               )
               A       :       List[Any]							=						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)
       A       :       Any							=						{}
       if origin_type is Literal or (isinstance(field.type    ,   _UpperCAmelCase					) and issubclass(field.type    ,   _UpperCAmelCase					)):
           if origin_type is Literal:
               A       :       int							=						field.type.__args__
           else:
               A       :       List[Any]							=						[x.value for x in field.type]

           A       :       List[Any]							=						make_choice_type_function(kwargs['''choices''']					)

           if field.default is not dataclasses.MISSING:
               A       :       int							=						field.default
           else:
               A       :       Dict							=						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
           A       :       Optional[int]							=						copy(_UpperCAmelCase					)

           # Hack because type=bool in argparse does not behave as we want.
           A       :       Optional[int]							=						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.
               A       :       List[str]							=						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
               A       :       Dict							=						default
               # This tells argparse we accept 0 or 1 value after --field_name
               A       :       List[Any]							=						'''?'''
               # This is the value that will get picked if we do --field_name (without value)
               A       :       Optional[int]							=						True
       elif isclass(_UpperCAmelCase					) and issubclass(_UpperCAmelCase    ,   _UpperCAmelCase					):
           A       :       Any							=						field.type.__args__[0]
           A       :       Tuple							=						'''+'''
           if field.default_factory is not dataclasses.MISSING:
               A       :       Union[str, Any]							=						field.default_factory()
           elif field.default is dataclasses.MISSING:
               A       :       Dict							=						True
       else:
           A       :       Union[str, Any]							=						field.type
           if field.default is not dataclasses.MISSING:
               A       :       int							=						field.default
           elif field.default_factory is not dataclasses.MISSING:
               A       :       Optional[int]							=						field.default_factory()
           else:
               A       :       Union[str, Any]							=						True
       parser.add_argument(_UpperCAmelCase    ,   *_UpperCAmelCase    ,   **_UpperCAmelCase					)

       # 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]):
           A       :       Dict							=						False
           parser.add_argument(f'''--no_{field.name}'''    ,   action='''store_false'''    ,   dest=field.name    ,   **_UpperCAmelCase					)


   def 					snake_case				( self    ,   _UpperCAmelCase					):
       if hasattr(_UpperCAmelCase    ,   '''_argument_group_name'''					):
           A       :       Dict							=						self.add_argument_group(dtype._argument_group_name					)
       else:
           A       :       Tuple							=						self

       try:
           A       :       Dict[str, type]							=						get_type_hints(_UpperCAmelCase					)
       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(_UpperCAmelCase					):
               A       :       Tuple							=						'''.'''.join(map(_UpperCAmelCase    ,   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(_UpperCAmelCase					):
           if not field.init:
               continue
           A       :       Any							=						type_hints[field.name]
           self._parse_dataclass_field(_UpperCAmelCase    ,   _UpperCAmelCase					)


   def 					snake_case				( self    ,   _UpperCAmelCase=None    ,   _UpperCAmelCase=False    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=None    ,   _UpperCAmelCase=None    ,   ):

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

           if args_filename:
               args_files.append(Path(_UpperCAmelCase					)					)
           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
               A       :       List[Any]							=						ArgumentParser()
               args_file_parser.add_argument(_UpperCAmelCase    ,   type=_UpperCAmelCase    ,   action='''append'''					)

               # Use only remaining args for further parsing (remove the args_file_flag)
               A,	A       :       Union[str, Any]							=						args_file_parser.parse_known_args(args=_UpperCAmelCase					)
               A       :       List[Any]							=						vars(_UpperCAmelCase					).get(args_file_flag.lstrip('''-'''					)    ,   _UpperCAmelCase					)

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

           A       :       Any							=						[]
           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
           A       :       int							=						file_args + args if args is not None else file_args + sys.argv[1:]
       A,	A       :       Dict							=						self.parse_known_args(args=_UpperCAmelCase					)
       A       :       Any							=						[]
       for dtype in self.dataclass_types:
           A       :       List[Any]							=						{f.name for f in dataclasses.fields(_UpperCAmelCase					) if f.init}
           A       :       Any							=						{k: v for k, v in vars(_UpperCAmelCase					).items() if k in keys}
           for k in keys:
               delattr(_UpperCAmelCase    ,   _UpperCAmelCase					)
           A       :       Optional[int]							=						dtype(**_UpperCAmelCase					)
           outputs.append(_UpperCAmelCase					)
       if len(namespace.__dict__					) > 0:
           # additional namespace.
           outputs.append(_UpperCAmelCase					)
       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 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase = False					):
       A       :       List[Any]							=						set(args.keys()					)
       A       :       Optional[int]							=						[]
       for dtype in self.dataclass_types:
           A       :       List[Any]							=						{f.name for f in dataclasses.fields(_UpperCAmelCase					) if f.init}
           A       :       Union[str, Any]							=						{k: v for k, v in args.items() if k in keys}
           unused_keys.difference_update(inputs.keys()					)
           A       :       Dict							=						dtype(**_UpperCAmelCase					)
           outputs.append(_UpperCAmelCase					)
       if not allow_extra_keys and unused_keys:
           raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(_UpperCAmelCase					)}'''					)
       return tuple(_UpperCAmelCase					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase = False					):
       with open(Path(_UpperCAmelCase					)    ,   encoding='''utf-8'''					) as open_json_file:
           A       :       Any							=						json.loads(open_json_file.read()					)
       A       :       Optional[Any]							=						self.parse_dict(_UpperCAmelCase    ,   allow_extra_keys=_UpperCAmelCase					)
       return tuple(_UpperCAmelCase					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase = False					):
       A       :       str							=						self.parse_dict(yaml.safe_load(Path(_UpperCAmelCase					).read_text()					)    ,   allow_extra_keys=_UpperCAmelCase					)
       return tuple(_UpperCAmelCase					)







'''simple docstring'''






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

import os
from pathlib import Path
def 							_lowerCamelCase(  UpperCamelCase__    : List[Any]    ,       UpperCamelCase__    : Optional[Any]    ,       UpperCamelCase__    : List[Any]		)		->  List[Any]:
    A       :       Any							=						{
        '''en''': '''Machine learning is great, isn\'t it?''',
        '''ru''': '''Машинное обучение - это здорово, не так ли?''',
        '''de''': '''Maschinelles Lernen ist großartig, oder?''',
    }

    # BLUE scores as follows:
    # "pair": [fairseq, transformers]
    A       :       List[Any]							=						{
        '''ru-en''': ['''[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)''', '''39.20'''],
        '''en-ru''': ['''[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)''', '''33.47'''],
        '''en-de''': ['''[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)''', '''42.83'''],
        '''de-en''': ['''[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)''', '''41.35'''],
    }
    A       :       List[Any]							=						F'''{src_lang}-{tgt_lang}'''

    A       :       Any							=						F'''
---
language: 
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- facebook
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.

For more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).

The abbreviation FSMT stands for FairSeqMachineTranslation

All four models are available:

* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)
* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)
* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)
* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)

## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = "facebook/wmt19-{src_lang}-{tgt_lang}"
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

- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)

## Training data

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

## Eval results

pair   | fairseq | transformers
-------|---------|----------
{pair}  | {scores[pair][0]} | {scores[pair][1]}

The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:
- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).
- re-ranking

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=15
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 facebook/wmt19-$PAIR $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
```
note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.

## 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

```bibtex
@inproceedings{{...,
  year={{2020}},
  title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},
  author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},
  booktitle={{Proc. of WMT}},
}}
```


## TODO

- port model ensemble (fairseq uses 4 model checkpoints)

'''
    os.makedirs(UpperCamelCase__    ,       exist_ok=UpperCamelCase__		)
    A       :       Optional[int]							=						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
snake_case_     =	Path(__file__).resolve().parent.parent.parent
snake_case_     =	repo_dir / """model_cards"""

for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
     snake_case_ ,  snake_case_ ,  snake_case_     =	model_name.split("""-""")
     snake_case_     =	model_cards_dir / """facebook""" / model_name
     write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
