
import gc
import unittest

from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_gpu,
    slow,
)

from .test_pipelines_common import ANY

@is_pipeline_test
class        snake_case__    (unittest.TestCase		):







						"""simple docstring"""




						__lowerCAmelCase					:Dict      =					MODEL_FOR_MASKED_LM_MAPPING
						__lowerCAmelCase					:Optional[int]      =					TF_MODEL_FOR_MASKED_LM_MAPPING

						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				str:
									"""simple docstring"""




									super().tearDown()
									# clean-up as much as possible GPU memory occupied by PyTorch
									gc.collect()
									if is_torch_available():
												import torch

												torch.cuda.empty_cache()

						@require_tf
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				List[str]:
									"""simple docstring"""




									a__       :						List[Any]							=  pipeline(task="""fill-mask""" ,       model="""sshleifer/tiny-distilroberta-base""" ,       top_k=2 ,       framework="""tf"""  )
									a__       :						List[Any]							=  unmasker("""My name is <mask>"""  )
									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        {"""sequence""": """My name is grouped""", """score""": 2.1E-05, """token""": 3_8_0_1_5, """token_str""": """ grouped"""},
									        {"""sequence""": """My name is accuser""", """score""": 2.1E-05, """token""": 2_5_5_0_6, """token_str""": """ accuser"""},
									    ] ,       )

									a__       :						Tuple							=  unmasker("""The largest city in France is <mask>"""  )
									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        {
									            """sequence""": """The largest city in France is grouped""",
									            """score""": 2.1E-05,
									            """token""": 3_8_0_1_5,
									            """token_str""": """ grouped""",
									        },
									        {
									            """sequence""": """The largest city in France is accuser""",
									            """score""": 2.1E-05,
									            """token""": 2_5_5_0_6,
									            """token_str""": """ accuser""",
									        },
									    ] ,       )

									a__       :						Dict							=  unmasker("""My name is <mask>""" ,       targets=[""" Patrick""", """ Clara""", """ Teven"""] ,       top_k=3  )
									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 1_3_6_0_6, """token_str""": """ Clara"""},
									        {"""sequence""": """My name is Patrick""", """score""": 2E-05, """token""": 3_4_9_9, """token_str""": """ Patrick"""},
									        {"""sequence""": """My name is Te""", """score""": 1.9E-05, """token""": 2_9_4_1, """token_str""": """ Te"""},
									    ] ,       )

						@require_torch
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				str:
									"""simple docstring"""




									a__       :						Any							=  pipeline(task="""fill-mask""" ,       model="""sshleifer/tiny-distilroberta-base""" ,       top_k=2 ,       framework="""pt"""  )

									a__       :						List[Any]							=  unmasker("""My name is <mask>"""  )
									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        {"""sequence""": """My name is Maul""", """score""": 2.2E-05, """token""": 3_5_6_7_6, """token_str""": """ Maul"""},
									        {"""sequence""": """My name isELS""", """score""": 2.2E-05, """token""": 1_6_4_1_6, """token_str""": """ELS"""},
									    ] ,       )

									a__       :						Union[str, Any]							=  unmasker("""The largest city in France is <mask>"""  )
									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        {
									            """sequence""": """The largest city in France is Maul""",
									            """score""": 2.2E-05,
									            """token""": 3_5_6_7_6,
									            """token_str""": """ Maul""",
									        },
									        {"""sequence""": """The largest city in France isELS""", """score""": 2.2E-05, """token""": 1_6_4_1_6, """token_str""": """ELS"""},
									    ] ,       )

									a__       :						int							=  unmasker("""My name is <mask>""" ,       targets=[""" Patrick""", """ Clara""", """ Teven"""] ,       top_k=3  )
									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        {"""sequence""": """My name is Patrick""", """score""": 2.1E-05, """token""": 3_4_9_9, """token_str""": """ Patrick"""},
									        {"""sequence""": """My name is Te""", """score""": 2E-05, """token""": 2_9_4_1, """token_str""": """ Te"""},
									        {"""sequence""": """My name is Clara""", """score""": 2E-05, """token""": 1_3_6_0_6, """token_str""": """ Clara"""},
									    ] ,       )

									a__       :						List[str]							=  unmasker("""My name is <mask> <mask>""" ,       top_k=2  )

									self.assertEqual(
									    nested_simplify(snake_case__ ,       decimals=6  ) ,       [
									        [
									            {
									                """score""": 2.2E-05,
									                """token""": 3_5_6_7_6,
									                """token_str""": """ Maul""",
									                """sequence""": """<s>My name is Maul<mask></s>""",
									            },
									            {"""score""": 2.2E-05, """token""": 1_6_4_1_6, """token_str""": """ELS""", """sequence""": """<s>My name isELS<mask></s>"""},
									        ],
									        [
									            {
									                """score""": 2.2E-05,
									                """token""": 3_5_6_7_6,
									                """token_str""": """ Maul""",
									                """sequence""": """<s>My name is<mask> Maul</s>""",
									            },
									            {"""score""": 2.2E-05, """token""": 1_6_4_1_6, """token_str""": """ELS""", """sequence""": """<s>My name is<mask>ELS</s>"""},
									        ],
									    ] ,       )

						@require_torch_gpu
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				int:
									"""simple docstring"""




									a__       :						Optional[int]							=  pipeline("""fill-mask""" ,       model="""hf-internal-testing/tiny-random-distilbert""" ,       device=0 ,       framework="""pt"""  )

									# convert model to fp16
									pipe.model.half()

									a__       :						Dict							=  pipe("""Paris is the [MASK] of France."""  )
									# We actually don't care about the result, we just want to make sure
									# it works, meaning the float16 tensor got casted back to float32
									# for postprocessing.
									self.assertIsInstance(snake_case__ ,       snake_case__  )

						@slow
						@require_torch
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						str							=  pipeline(task="""fill-mask""" ,       model="""distilroberta-base""" ,       top_k=2 ,       framework="""pt"""  )
									self.run_large_test(snake_case__  )

						@slow
						@require_tf
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						Union[str, Any]							=  pipeline(task="""fill-mask""" ,       model="""distilroberta-base""" ,       top_k=2 ,       framework="""tf"""  )
									self.run_large_test(snake_case__  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase  ) ->				int:
									"""simple docstring"""




									a__       :						Union[str, Any]							=  unmasker("""My name is <mask>"""  )
									self.assertEqual(
									    nested_simplify(snake_case__  ) ,       [
									        {"""sequence""": """My name is John""", """score""": 0.0_0_8, """token""": 6_1_0, """token_str""": """ John"""},
									        {"""sequence""": """My name is Chris""", """score""": 0.0_0_7, """token""": 1_5_7_3, """token_str""": """ Chris"""},
									    ] ,       )
									a__       :						int							=  unmasker("""The largest city in France is <mask>"""  )
									self.assertEqual(
									    nested_simplify(snake_case__  ) ,       [
									        {
									            """sequence""": """The largest city in France is Paris""",
									            """score""": 0.2_5_1,
									            """token""": 2_2_0_1,
									            """token_str""": """ Paris""",
									        },
									        {
									            """sequence""": """The largest city in France is Lyon""",
									            """score""": 0.2_1_4,
									            """token""": 1_2_7_9_0,
									            """token_str""": """ Lyon""",
									        },
									    ] ,       )

									a__       :						int							=  unmasker("""My name is <mask>""" ,       targets=[""" Patrick""", """ Clara""", """ Teven"""] ,       top_k=3  )
									self.assertEqual(
									    nested_simplify(snake_case__  ) ,       [
									        {"""sequence""": """My name is Patrick""", """score""": 0.0_0_5, """token""": 3_4_9_9, """token_str""": """ Patrick"""},
									        {"""sequence""": """My name is Clara""", """score""": 0.0_0_0, """token""": 1_3_6_0_6, """token_str""": """ Clara"""},
									        {"""sequence""": """My name is Te""", """score""": 0.0_0_0, """token""": 2_9_4_1, """token_str""": """ Te"""},
									    ] ,       )

						@require_torch
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Any:
									"""simple docstring"""




									a__       :						Any							=  pipeline(task="""fill-mask""" ,       model="""sshleifer/tiny-distilroberta-base""" ,       framework="""pt"""  )
									a__       :						List[str]							=  None
									a__       :						str							=  None
									self.run_pipeline_test(snake_case__ ,       []  )

						@require_tf
						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Dict:
									"""simple docstring"""




									a__       :						List[str]							=  pipeline(task="""fill-mask""" ,       model="""sshleifer/tiny-distilroberta-base""" ,       framework="""tf"""  )
									a__       :						str							=  None
									a__       :						Dict							=  None
									self.run_pipeline_test(snake_case__ ,       []  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase ,       __lowercase  ) ->				Any:
									"""simple docstring"""




									if tokenizer is None or tokenizer.mask_token_id is None:
												self.skipTest("""The provided tokenizer has no mask token, (probably reformer or wav2vec2)"""  )

									a__       :						Any							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__  )
									a__       :						int							=  [
									    F'''This is another {tokenizer.mask_token} test''',
									]
									return fill_masker, examples

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				Optional[int]:
									"""simple docstring"""




									a__       :						Any							=  fill_masker.tokenizer
									a__       :						Optional[int]							=  fill_masker.model

									a__       :						Dict							=  fill_masker(
									    F'''This is a {tokenizer.mask_token}''' ,       )
									self.assertEqual(
									    snake_case__ ,       [
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									    ] ,       )

									a__       :						int							=  fill_masker([F'''This is a {tokenizer.mask_token}''']  )
									self.assertEqual(
									    snake_case__ ,       [
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									    ] ,       )

									a__       :						Optional[Any]							=  fill_masker([F'''This is a {tokenizer.mask_token}''', F'''Another {tokenizer.mask_token} great test.''']  )
									self.assertEqual(
									    snake_case__ ,       [
									        [
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        ],
									        [
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        ],
									    ] ,       )

									with self.assertRaises(snake_case__  ):
												fill_masker([None]  )
									# No mask_token is not supported
									with self.assertRaises(snake_case__  ):
												fill_masker("""This is"""  )

									self.run_test_top_k(snake_case__ ,       snake_case__  )
									self.run_test_targets(snake_case__ ,       snake_case__  )
									self.run_test_top_k_targets(snake_case__ ,       snake_case__  )
									self.fill_mask_with_duplicate_targets_and_top_k(snake_case__ ,       snake_case__  )
									self.fill_mask_with_multiple_masks(snake_case__ ,       snake_case__  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				List[str]:
									"""simple docstring"""




									a__       :						List[str]							=  tokenizer.get_vocab()
									a__       :						List[str]							=  sorted(vocab.keys()  )[:2]
									# Pipeline argument
									a__       :						Any							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__ ,       targets=snake_case__  )
									a__       :						Tuple							=  fill_masker(F'''This is a {tokenizer.mask_token}'''  )
									self.assertEqual(
									    snake_case__ ,       [
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									    ] ,       )
									a__       :						int							=  {vocab[el] for el in targets}
									self.assertEqual({el["""token"""] for el in outputs} ,       snake_case__  )
									a__       :						Optional[Any]							=  [tokenizer.decode([x]  ) for x in target_ids]
									self.assertEqual({el["""token_str"""] for el in outputs} ,       set(snake_case__  )  )

									# Call argument
									a__       :						Union[str, Any]							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__  )
									a__       :						Optional[int]							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       targets=snake_case__  )
									self.assertEqual(
									    snake_case__ ,       [
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									    ] ,       )
									a__       :						Any							=  {vocab[el] for el in targets}
									self.assertEqual({el["""token"""] for el in outputs} ,       snake_case__  )
									a__       :						Optional[int]							=  [tokenizer.decode([x]  ) for x in target_ids]
									self.assertEqual({el["""token_str"""] for el in outputs} ,       set(snake_case__  )  )

									# Score equivalence
									a__       :						Any							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       targets=snake_case__  )
									a__       :						Union[str, Any]							=  [top_mask['''token_str'''] for top_mask in outputs]
									a__       :						Optional[int]							=  [top_mask['''score'''] for top_mask in outputs]

									# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
									if set(snake_case__  ) == set(snake_case__  ):
												a__       :						List[Any]							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       targets=snake_case__  )
												a__       :						List[str]							=  [top_mask['''score'''] for top_mask in unmasked_targets]
												self.assertEqual(nested_simplify(snake_case__  ) ,       nested_simplify(snake_case__  )  )

									# Raises with invalid
									with self.assertRaises(snake_case__  ):
												a__       :						int							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       targets=[]  )
									# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
									if "" not in tokenizer.get_vocab():
												with self.assertRaises(snake_case__  ):
															a__       :						int							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       targets=[""""""]  )
												with self.assertRaises(snake_case__  ):
															a__       :						Any							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       targets=""""""  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				Tuple:
									"""simple docstring"""




									a__       :						List[str]							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__ ,       top_k=2  )
									a__       :						Optional[Any]							=  fill_masker(F'''This is a {tokenizer.mask_token}'''  )
									self.assertEqual(
									    snake_case__ ,       [
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									    ] ,       )

									a__       :						Any							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__  )
									a__       :						List[Any]							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       top_k=2  )
									self.assertEqual(
									    snake_case__ ,       [
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									    ] ,       )
									self.assertEqual(nested_simplify(snake_case__  ) ,       nested_simplify(snake_case__  )  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				Optional[Any]:
									"""simple docstring"""




									a__       :						str							=  tokenizer.get_vocab()
									a__       :						int							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__  )

									# top_k=2, ntargets=3
									a__       :						Optional[Any]							=  sorted(vocab.keys()  )[:3]
									a__       :						str							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       top_k=2 ,       targets=snake_case__  )

									# If we use the most probably targets, and filter differently, we should still
									# have the same results
									a__       :						Tuple							=  [el['''token_str'''] for el in sorted(snake_case__ ,       key=lambda __lowercase  : x["score"] ,       reverse=snake_case__  )]
									# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
									if set(snake_case__  ).issubset(snake_case__  ):
												a__       :						str							=  fill_masker(F'''This is a {tokenizer.mask_token}''' ,       top_k=3 ,       targets=snake_case__  )
												# They should yield exactly the same result
												self.assertEqual(nested_simplify(snake_case__  ) ,       nested_simplify(snake_case__  )  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				Dict:
									"""simple docstring"""




									a__       :						str							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__  )
									a__       :						Union[str, Any]							=  tokenizer.get_vocab()
									# String duplicates + id duplicates
									a__       :						List[Any]							=  sorted(vocab.keys()  )[:3]
									a__       :						Optional[int]							=  [targets[0], targets[1], targets[0], targets[2], targets[1]]
									a__       :						str							=  fill_masker(F'''My name is {tokenizer.mask_token}''' ,       targets=snake_case__ ,       top_k=1_0  )

									# The target list contains duplicates, so we can't output more
									# than them
									self.assertEqual(len(snake_case__  ) ,       3  )

						def 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase  ) ->				List[Any]:
									"""simple docstring"""




									a__       :						Any							=  FillMaskPipeline(model=snake_case__ ,       tokenizer=snake_case__  )

									a__       :						Union[str, Any]							=  fill_masker(
									    F'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''' ,       top_k=2  )
									self.assertEqual(
									    snake_case__ ,       [
									        [
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        ],
									        [
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        ],
									        [
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									            {"""sequence""": ANY(snake_case__  ), """score""": ANY(snake_case__  ), """token""": ANY(snake_case__  ), """token_str""": ANY(snake_case__  )},
									        ],
									    ] ,       )









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

import datasets


_lowercase		:				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"

_lowercase		:				str      		="\\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"

_lowercase		:				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        snake_case__    (datasets.Metric		):







						"""simple docstring"""




						def 							SCREAMING_SNAKE_CASE__(       self  ) ->				Tuple:
									"""simple docstring"""




									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 							SCREAMING_SNAKE_CASE__(       self ,       __lowercase ,       __lowercase ,       __lowercase = False ,       __lowercase = False ,       __lowercase = False ,       __lowercase = False ,       ) ->				Any:
									"""simple docstring"""




									a__       :						Any							=  len(references[0]  )
									if any(len(__lowercase  ) != references_per_prediction for refs in references  ):
												raise ValueError("""Sacrebleu requires the same number of references for each prediction"""  )
									a__       :						str							=  [[refs[i] for refs in references] for i in range(__lowercase  )]

									a__       :						int							=  TER(
									    normalized=__lowercase ,       no_punct=__lowercase ,       asian_support=__lowercase ,       case_sensitive=__lowercase ,       )
									a__       :						Optional[int]							=  sb_ter.corpus_score(__lowercase ,       __lowercase  )

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




