





'''simple docstring'''






from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


snake_case_     =	logging.get_logger(__name__)


class   _lowercase						(							a				):
   _UpperCamelCase       		=   ["""input_features""", """attention_mask"""]


   def __init__( self    ,   _UpperCAmelCase=80    ,   _UpperCAmelCase=16_000    ,   _UpperCAmelCase=0.0    ,   _UpperCAmelCase=10    ,   _UpperCAmelCase=25    ,   _UpperCAmelCase="hamming_window"    ,   _UpperCAmelCase=32768.0    ,   _UpperCAmelCase=0.97    ,   _UpperCAmelCase=1.0    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=False    ,   **_UpperCAmelCase    ,   ):
       super().__init__(feature_size=_UpperCAmelCase    ,   sampling_rate=_UpperCAmelCase    ,   padding_value=_UpperCAmelCase    ,   **_UpperCAmelCase					)

       A       :       Any							=						feature_size
       A       :       int							=						sampling_rate
       A       :       Dict							=						padding_value
       A       :       str							=						hop_length
       A       :       str							=						win_length
       A       :       Dict							=						frame_signal_scale
       A       :       Optional[Any]							=						preemphasis_coeff
       A       :       List[Any]							=						mel_floor
       A       :       Optional[int]							=						normalize_means
       A       :       Optional[Any]							=						normalize_vars
       A       :       Tuple							=						win_function
       A       :       Union[str, Any]							=						return_attention_mask

       A       :       Union[str, Any]							=						win_length * sampling_rate // 1_000
       A       :       Tuple							=						hop_length * sampling_rate // 1_000

       A       :       Any							=						optimal_fft_length(self.sample_size					)
       A       :       List[Any]							=						(self.n_fft // 2) + 1


   def 					snake_case				( self    ,   _UpperCAmelCase					):
       if self.win_function == "hamming_window":
           A       :       int							=						window_function(window_length=self.sample_size    ,   name=self.win_function    ,   periodic=_UpperCAmelCase					)
       else:
           A       :       Optional[int]							=						window_function(window_length=self.sample_size    ,   name=self.win_function					)

       A       :       str							=						mel_filter_bank(
           num_frequency_bins=self.n_freqs    ,   num_mel_filters=self.feature_size    ,   min_frequency=0.0    ,   max_frequency=self.sampling_rate / 2.0    ,   sampling_rate=self.sampling_rate    ,   )

       A       :       List[str]							=						spectrogram(
           one_waveform * self.frame_signal_scale    ,   window=_UpperCAmelCase    ,   frame_length=self.sample_size    ,   hop_length=self.sample_stride    ,   fft_length=self.n_fft    ,   center=_UpperCAmelCase    ,   preemphasis=self.preemphasis_coeff    ,   mel_filters=_UpperCAmelCase    ,   mel_floor=self.mel_floor    ,   log_mel='''log'''    ,   )
       return msfc_features.T


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase					):
       # make sure we normalize float32 arrays
       if self.normalize_means:
           A       :       Dict							=						x[:input_length].mean(axis=0					)
           A       :       Optional[Any]							=						np.subtract(_UpperCAmelCase    ,   _UpperCAmelCase					)
       if self.normalize_vars:
           A       :       Tuple							=						x[:input_length].std(axis=0					)
           A       :       Optional[int]							=						np.divide(_UpperCAmelCase    ,   _UpperCAmelCase					)

       if input_length < x.shape[0]:
           A       :       Optional[int]							=						padding_value

       # make sure array is in float32
       A       :       Optional[Any]							=						x.astype(np.floataa					)

       return x


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase = None					):
       A       :       Any							=						attention_mask.sum(-1					) if attention_mask is not None else [x.shape[0] for x in input_features]
       return [self._normalize_one(_UpperCAmelCase    ,   _UpperCAmelCase    ,   self.padding_value					) for x, n in zip(_UpperCAmelCase    ,   _UpperCAmelCase					)]


   def __call__( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase = False    ,   _UpperCAmelCase = None    ,   _UpperCAmelCase = False    ,   _UpperCAmelCase = None    ,   _UpperCAmelCase = None    ,   _UpperCAmelCase = None    ,   _UpperCAmelCase = None    ,   **_UpperCAmelCase    ,   ):

       if sampling_rate is not None:
           if sampling_rate != self.sampling_rate:
               raise ValueError(
                   f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
                   f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
                   f''' {self.sampling_rate} and not {sampling_rate}.'''					)
       else:
           logger.warning(
               '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. '''
               '''Failing to do so can result in silent errors that might be hard to debug.'''					)

       A       :       List[Any]							=						isinstance(_UpperCAmelCase    ,   np.ndarray					) and len(raw_speech.shape					) > 1
       if is_batched_numpy and len(raw_speech.shape					) > 2:
           raise ValueError(f'''Only mono-channel audio is supported for input to {self}'''					)
       A       :       Optional[int]							=						is_batched_numpy or (
           isinstance(_UpperCAmelCase    ,   (list, tuple)					) and (isinstance(raw_speech[0]    ,   (np.ndarray, tuple, list)					))
       )

       if is_batched:
           A       :       Union[str, Any]							=						[np.asarray(_UpperCAmelCase    ,   dtype=np.floataa					) for speech in raw_speech]
       elif not is_batched and not isinstance(_UpperCAmelCase    ,   np.ndarray					):
           A       :       str							=						np.asarray(_UpperCAmelCase    ,   dtype=np.floataa					)
       elif isinstance(_UpperCAmelCase    ,   np.ndarray					) and raw_speech.dtype is np.dtype(np.floataa					):
           A       :       Optional[Any]							=						raw_speech.astype(np.floataa					)

       # always return batch
       if not is_batched:
           A       :       Any							=						[raw_speech]

       # extract fbank features
       A       :       Optional[Any]							=						[self._extract_mfsc_features(_UpperCAmelCase					) for one_waveform in raw_speech]

       # convert into correct format for padding
       A       :       List[Any]							=						BatchFeature({'''input_features''': features}					)

       A       :       int							=						self.pad(
           _UpperCAmelCase    ,   padding=_UpperCAmelCase    ,   max_length=_UpperCAmelCase    ,   truncation=_UpperCAmelCase    ,   pad_to_multiple_of=_UpperCAmelCase    ,   return_attention_mask=_UpperCAmelCase    ,   **_UpperCAmelCase    ,   )
       # make sure list is in array format
       A       :       Optional[Any]							=						padded_inputs.get('''input_features'''					)
       if isinstance(input_features[0]    ,   _UpperCAmelCase					):
           A       :       List[Any]							=						[np.asarray(_UpperCAmelCase    ,   dtype=np.floataa					) for feature in input_features]

       A       :       int							=						padded_inputs.get('''attention_mask'''					)
       if attention_mask is not None:
           A       :       List[str]							=						[np.asarray(_UpperCAmelCase    ,   dtype=np.intaa					) for array in attention_mask]

       if self.normalize_means or self.normalize_vars:
           A       :       List[Any]							=						(
               np.array(_UpperCAmelCase    ,   dtype=np.intaa					)
               if self._get_padding_strategies(_UpperCAmelCase    ,   max_length=_UpperCAmelCase					) is not PaddingStrategy.DO_NOT_PAD
               and padding
               else None
           )
           A       :       Optional[Any]							=						self.normalize(
               padded_inputs['''input_features''']    ,   attention_mask=_UpperCAmelCase					)

       if return_tensors is not None:
           A       :       str							=						padded_inputs.convert_to_tensors(_UpperCAmelCase					)

       return padded_inputs







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