
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_SCREAMING_SNAKE_CASE    :      Dict          =			logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE    :      Dict          =			'▁'

_SCREAMING_SNAKE_CASE    :      Optional[int]          =			{
    'vocab_file': 'vocab.json',
    'spm_file': 'sentencepiece.bpe.model',
}

_SCREAMING_SNAKE_CASE    :      List[Any]          =			{
    'vocab_file': {
        'facebook/s2t-small-librispeech-asr': (
            'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json'
        ),
    },
    'spm_file': {
        'facebook/s2t-small-librispeech-asr': (
            'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model'
        )
    },
}

_SCREAMING_SNAKE_CASE    :      Any          =			{
    'facebook/s2t-small-librispeech-asr': 1_0_2_4,
}

_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de']

_SCREAMING_SNAKE_CASE    :      Dict          =			{'mustc': MUSTC_LANGS}







class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				VOCAB_FILES_NAMES
	_lowerCAmelCase							       =				PRETRAINED_VOCAB_FILES_MAP
	_lowerCAmelCase							       =				MAX_MODEL_INPUT_SIZES
	_lowerCAmelCase							       =				["input_ids", "attention_mask"]

	_lowerCAmelCase							       =				[]





	def __init__(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__="<s>"				,       UpperCamelCase__="</s>"				,       UpperCamelCase__="<pad>"				,       UpperCamelCase__="<unk>"				,       UpperCamelCase__=False				,       UpperCamelCase__=False				,       UpperCamelCase__=None				,       UpperCamelCase__=None				,       UpperCamelCase__ = None				,       **UpperCamelCase__				,       ):
					A__  :	Optional[Any]         =							{} if sp_model_kwargs is None else sp_model_kwargs

					super().__init__(
					    bos_token=UpperCamelCase__				,       eos_token=UpperCamelCase__				,       unk_token=UpperCamelCase__				,       pad_token=UpperCamelCase__				,       do_upper_case=UpperCamelCase__				,       do_lower_case=UpperCamelCase__				,       tgt_lang=UpperCamelCase__				,       lang_codes=UpperCamelCase__				,       sp_model_kwargs=self.sp_model_kwargs				,       **UpperCamelCase__				,       )
					A__  :	int         =							do_upper_case
					A__  :	List[str]         =							do_lower_case

					A__  :	List[Any]         =							load_json(UpperCamelCase__		)
					A__  :	str         =							{v: k for k, v in self.encoder.items()}
					A__  :	Union[str, Any]         =							spm_file
					A__  :	int         =							load_spm(UpperCamelCase__				,       self.sp_model_kwargs		)

					if lang_codes is not None:
									A__  :	Tuple         =							lang_codes
									A__  :	Any         =							LANGUAGES[lang_codes]
									A__  :	Any         =							[F"<lang:{lang}>" for lang in self.langs]
									A__  :	Optional[int]         =							{lang: self.sp_model.PieceToId(F"<lang:{lang}>"		) for lang in self.langs}

									A__  :	Any         =							self.lang_tokens
									A__  :	str         =							tgt_lang if tgt_lang is not None else self.langs[0]

									self.set_tgt_lang_special_tokens(self._tgt_lang		)
					else:
									A__  :	str         =							{}





	@property
	def   __snake_case				(			self		):
					return len(self.encoder		)





	@property
	def   __snake_case				(			self		):
					return self._tgt_lang





	@tgt_lang.setter
	def   __snake_case				(			self				,       UpperCamelCase__		):
					A__  :	List[Any]         =							new_tgt_lang
					self.set_tgt_lang_special_tokens(UpperCamelCase__		)





	def   __snake_case				(			self				,       UpperCamelCase__		):
					A__  :	Optional[Any]         =							self.lang_code_to_id[tgt_lang]
					A__  :	Optional[Any]         =							[lang_code_id]





	def   __snake_case				(			self				,       UpperCamelCase__		):
					return self.sp_model.encode(UpperCamelCase__				,       out_type=UpperCamelCase__		)





	def   __snake_case				(			self				,       UpperCamelCase__		):
					return self.encoder.get(UpperCamelCase__				,       self.encoder[self.unk_token]		)





	def   __snake_case				(			self				,       UpperCamelCase__		):
					return self.decoder.get(UpperCamelCase__				,       self.unk_token		)





	def   __snake_case				(			self				,       UpperCamelCase__		):
					A__  :	Tuple         =							[]
					A__  :	Optional[int]         =							''''''
					for token in tokens:
									# make sure that special tokens are not decoded using sentencepiece model
									if token in self.all_special_tokens:
													A__  :	Any         =							self.sp_model.decode(UpperCamelCase__		)
													out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
													A__  :	List[Any]         =							[]
									else:
													current_sub_tokens.append(UpperCamelCase__		)
					A__  :	List[Any]         =							self.sp_model.decode(UpperCamelCase__		)
					out_string += decoded.upper() if self.do_upper_case else decoded
					return out_string.strip()





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__=None		):
					if token_ids_a is None:
									return self.prefix_tokens + token_ids_a + [self.eos_token_id]
					# We don't expect to process pairs, but leave the pair logic for API consistency
					return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__ = None				,       UpperCamelCase__ = False		):

					if already_has_special_tokens:
									return super().get_special_tokens_mask(
									    token_ids_a=UpperCamelCase__				,       token_ids_a=UpperCamelCase__				,       already_has_special_tokens=UpperCamelCase__		)

					A__  :	Optional[Any]         =							[1] * len(self.prefix_tokens		)
					A__  :	Optional[Any]         =							[1]
					if token_ids_a is None:
									return prefix_ones + ([0] * len(UpperCamelCase__		)) + suffix_ones
					return prefix_ones + ([0] * len(UpperCamelCase__		)) + ([0] * len(UpperCamelCase__		)) + suffix_ones





	def   __snake_case				(			self		):
					A__  :	Optional[int]         =							self.encoder.copy()
					vocab.update(self.added_tokens_encoder		)
					return vocab





	def __getstate__(			self		):
					A__  :	Optional[int]         =							self.__dict__.copy()
					A__  :	Any         =							None
					return state





	def __setstate__(			self				,       UpperCamelCase__		):
					A__  :	str         =							d

					# for backward compatibility
					if not hasattr(self				,       '''sp_model_kwargs'''		):
									A__  :	int         =							{}

					A__  :	str         =							load_spm(self.spm_file				,       self.sp_model_kwargs		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__ = None		):
					A__  :	int         =							Path(UpperCamelCase__		)
					assert save_dir.is_dir(), F"{save_directory} should be a directory"
					A__  :	Optional[Any]         =							save_dir / (
					    (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file''']
					)
					A__  :	List[Any]         =							save_dir / (
					    (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file''']
					)

					save_json(self.encoder				,       UpperCamelCase__		)

					if os.path.abspath(self.spm_file		) != os.path.abspath(UpperCamelCase__		) and os.path.isfile(self.spm_file		):
									copyfile(self.spm_file				,       UpperCamelCase__		)
					elif not os.path.isfile(self.spm_file		):
									with open(UpperCamelCase__				,       '''wb'''		) as fi:
													A__  :	str         =							self.sp_model.serialized_model_proto()
													fi.write(UpperCamelCase__		)

					return (str(UpperCamelCase__		), str(UpperCamelCase__		))




def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str							,						__UpperCamelCase :						Dict[str, Any]       ) ->       sentencepiece.SentencePieceProcessor:

				"""simple docstring"""







				A__  :	List[Any]         =							sentencepiece.SentencePieceProcessor(**__UpperCamelCase       )
				spm.Load(str(__UpperCamelCase       )       )
				return spm

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       Union[Dict, List]:

				"""simple docstring"""







				with open(__UpperCamelCase							,						'''r'''       ) as f:
								return json.load(__UpperCamelCase       )



def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]							,						__UpperCamelCase :						str       ) ->       None:

				"""simple docstring"""







				with open(__UpperCamelCase							,						'''w'''       ) as f:
								json.dump(__UpperCamelCase							,						__UpperCamelCase							,						indent=2       )

import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			'\\n@inproceedings{snover-etal-2006-study,\n    title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n    author = "Snover, Matthew  and\n      Dorr, Bonnie  and\n      Schwartz, Rich  and\n      Micciulla, Linnea  and\n      Makhoul, John",\n    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n    month = aug # " 8-12",\n    year = "2006",\n    address = "Cambridge, Massachusetts, USA",\n    publisher = "Association for Machine Translation in the Americas",\n    url = "https://aclanthology.org/2006.amta-papers.25",\n    pages = "223--231",\n}\n@inproceedings{post-2018-call,\n    title = "A Call for Clarity in Reporting {BLEU} Scores",\n    author = "Post, Matt",\n    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n    month = oct,\n    year = "2018",\n    address = "Belgium, Brussels",\n    publisher = "Association for Computational Linguistics",\n    url = "https://www.aclweb.org/anthology/W18-6319",\n    pages = "186--191",\n}\n'

_SCREAMING_SNAKE_CASE    :      Tuple          =			'\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n'

_SCREAMING_SNAKE_CASE    :      Optional[Any]          =			'\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n    predictions (list of str): The system stream (a sequence of segments).\n    references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n                                    Only applies if `normalized = True`. Defaults to `False`.\n    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n    \'num_edits\' (int): The cumulative number of edits\n    \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n    Example 1:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?",\n        ...                     "What did the TER metric user say to the developer?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n        ...             ["Your jokes are...", "...TERrible"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n    Example 2:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n    Example 3:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         normalized=True,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n    Example 4:\n        >>> predictions = ["does this sentence match??",\n        ...                     "what about this sentence?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n    Example 5:\n        >>> predictions = ["does this sentence match??",\n        ...                    "what about this sentence?",\n        ...                    "What did the TER metric user say to the developer?"]\n        >>> references = [["does this sentence match", "does this sentence match!?!"],\n        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n        ...             ["Your jokes are...", "...TERrible"]]\n        >>> ter = datasets.load_metric("ter")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n'







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,			_KWARGS_DESCRIPTION   )
class  UpperCamelCase__		(    datasets.Metric   ):







	'''simple docstring'''





	def   __snake_case				(			self		):
					if version.parse(scb.__version__		) < version.parse('''1.4.12'''		):
									raise ImportWarning(
									    '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'''
									    '''You can install it with `pip install "sacrebleu>=1.4.12"`.'''		)
					return datasets.MetricInfo(
					    description=_DESCRIPTION				,       citation=_CITATION				,       homepage='''http://www.cs.umd.edu/~snover/tercom/'''				,       inputs_description=_KWARGS_DESCRIPTION				,       features=datasets.Features(
					        {
					            '''predictions''': datasets.Value('''string'''				,       id='''sequence'''		),
					            '''references''': datasets.Sequence(datasets.Value('''string'''				,       id='''sequence'''		)				,       id='''references'''		),
					        }		)				,       codebase_urls=['''https://github.com/mjpost/sacreBLEU#ter''']				,       reference_urls=[
					        '''https://github.com/jhclark/tercom''',
					    ]				,       )





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__ = False				,       UpperCamelCase__ = False				,       UpperCamelCase__ = False				,       UpperCamelCase__ = False				,       ):
					A__  :	List[Any]         =							len(references[0]		)
					if any(len(UpperCamelCase__		) != references_per_prediction for refs in references		):
									raise ValueError('''Sacrebleu requires the same number of references for each prediction'''		)
					A__  :	Dict         =							[[refs[i] for refs in references] for i in range(UpperCamelCase__		)]

					A__  :	Optional[Any]         =							TER(
					    normalized=UpperCamelCase__				,       no_punct=UpperCamelCase__				,       asian_support=UpperCamelCase__				,       case_sensitive=UpperCamelCase__				,       )
					A__  :	str         =							sb_ter.corpus_score(UpperCamelCase__				,       UpperCamelCase__		)

					return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}