

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 	UpperCAmelCase__		(	unittest.TestCase	):






  """simple docstring"""


  a									= MODEL_FOR_MASKED_LM_MAPPING
  a									= TF_MODEL_FOR_MASKED_LM_MAPPING






  def 				lowercase_		(							self						:		str )		->							Any:
       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 				lowercase_		(							self						:		Optional[Any] )		->							List[Any]:
       SCREAMING_SNAKE_CASE__   =   pipeline(task='''fill-mask'''     ,       model='''sshleifer/tiny-distilroberta-base'''     ,       top_k=2     ,       framework='''tf''' )
       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask>''' )
       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               {'''sequence''': '''My name is grouped''', '''score''': 2.1e-05, '''token''': 3_8015, '''token_str''': ''' grouped'''},
               {'''sequence''': '''My name is accuser''', '''score''': 2.1e-05, '''token''': 2_5506, '''token_str''': ''' accuser'''},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   unmasker('''The largest city in France is <mask>''' )
       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               {
                   '''sequence''': '''The largest city in France is grouped''',
                   '''score''': 2.1e-05,
                   '''token''': 3_8015,
                   '''token_str''': ''' grouped''',
               },
               {
                   '''sequence''': '''The largest city in France is accuser''',
                   '''score''': 2.1e-05,
                   '''token''': 2_5506,
                   '''token_str''': ''' accuser''',
               },
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask>'''     ,       targets=[''' Patrick''', ''' Clara''', ''' Teven''']     ,       top_k=3 )
       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 1_3606, '''token_str''': ''' Clara'''},
               {'''sequence''': '''My name is Patrick''', '''score''': 2e-05, '''token''': 3499, '''token_str''': ''' Patrick'''},
               {'''sequence''': '''My name is Te''', '''score''': 1.9e-05, '''token''': 2941, '''token_str''': ''' Te'''},
           ]     ,       )






  @require_torch
  def 				lowercase_		(							self						:		List[Any] )		->							List[str]:
       SCREAMING_SNAKE_CASE__   =   pipeline(task='''fill-mask'''     ,       model='''sshleifer/tiny-distilroberta-base'''     ,       top_k=2     ,       framework='''pt''' )

       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask>''' )
       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               {'''sequence''': '''My name is Maul''', '''score''': 2.2e-05, '''token''': 3_5676, '''token_str''': ''' Maul'''},
               {'''sequence''': '''My name isELS''', '''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS'''},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   unmasker('''The largest city in France is <mask>''' )
       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               {
                   '''sequence''': '''The largest city in France is Maul''',
                   '''score''': 2.2e-05,
                   '''token''': 3_5676,
                   '''token_str''': ''' Maul''',
               },
               {'''sequence''': '''The largest city in France isELS''', '''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS'''},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask>'''     ,       targets=[''' Patrick''', ''' Clara''', ''' Teven''']     ,       top_k=3 )
       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               {'''sequence''': '''My name is Patrick''', '''score''': 2.1e-05, '''token''': 3499, '''token_str''': ''' Patrick'''},
               {'''sequence''': '''My name is Te''', '''score''': 2e-05, '''token''': 2941, '''token_str''': ''' Te'''},
               {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 1_3606, '''token_str''': ''' Clara'''},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask> <mask>'''     ,       top_k=2 )

       self.assertEqual(
           nested_simplify(__lowerCamelCase     ,       decimals=6 )     ,       [
               [
                   {
                       '''score''': 2.2e-05,
                       '''token''': 3_5676,
                       '''token_str''': ''' Maul''',
                       '''sequence''': '''<s>My name is Maul<mask></s>''',
                   },
                   {'''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name isELS<mask></s>'''},
               ],
               [
                   {
                       '''score''': 2.2e-05,
                       '''token''': 3_5676,
                       '''token_str''': ''' Maul''',
                       '''sequence''': '''<s>My name is<mask> Maul</s>''',
                   },
                   {'''score''': 2.2e-05, '''token''': 1_6416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name is<mask>ELS</s>'''},
               ],
           ]     ,       )






  @require_torch_gpu
  def 				lowercase_		(							self						:		Dict )		->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__   =   pipeline('''fill-mask'''     ,       model='''hf-internal-testing/tiny-random-distilbert'''     ,       device=0     ,       framework='''pt''' )

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

       SCREAMING_SNAKE_CASE__   =   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(__lowerCamelCase     ,       __lowerCamelCase )






  @slow
  @require_torch
  def 				lowercase_		(							self						:		List[str] )		->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__   =   pipeline(task='''fill-mask'''     ,       model='''distilroberta-base'''     ,       top_k=2     ,       framework='''pt''' )
       self.run_large_test(__lowerCamelCase )






  @slow
  @require_tf
  def 				lowercase_		(							self						:		str )		->							Dict:
       SCREAMING_SNAKE_CASE__   =   pipeline(task='''fill-mask'''     ,       model='''distilroberta-base'''     ,       top_k=2     ,       framework='''tf''' )
       self.run_large_test(__lowerCamelCase )






  def 				lowercase_		(							self						:		Optional[int]     ,       __lowerCamelCase						:		Optional[Any] )		->							Optional[Any]:
       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask>''' )
       self.assertEqual(
           nested_simplify(__lowerCamelCase )     ,       [
               {'''sequence''': '''My name is John''', '''score''': 0.008, '''token''': 610, '''token_str''': ''' John'''},
               {'''sequence''': '''My name is Chris''', '''score''': 0.007, '''token''': 1573, '''token_str''': ''' Chris'''},
           ]     ,       )
       SCREAMING_SNAKE_CASE__   =   unmasker('''The largest city in France is <mask>''' )
       self.assertEqual(
           nested_simplify(__lowerCamelCase )     ,       [
               {
                   '''sequence''': '''The largest city in France is Paris''',
                   '''score''': 0.251,
                   '''token''': 2201,
                   '''token_str''': ''' Paris''',
               },
               {
                   '''sequence''': '''The largest city in France is Lyon''',
                   '''score''': 0.214,
                   '''token''': 1_2790,
                   '''token_str''': ''' Lyon''',
               },
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   unmasker('''My name is <mask>'''     ,       targets=[''' Patrick''', ''' Clara''', ''' Teven''']     ,       top_k=3 )
       self.assertEqual(
           nested_simplify(__lowerCamelCase )     ,       [
               {'''sequence''': '''My name is Patrick''', '''score''': 0.005, '''token''': 3499, '''token_str''': ''' Patrick'''},
               {'''sequence''': '''My name is Clara''', '''score''': 0.000, '''token''': 1_3606, '''token_str''': ''' Clara'''},
               {'''sequence''': '''My name is Te''', '''score''': 0.000, '''token''': 2941, '''token_str''': ''' Te'''},
           ]     ,       )






  @require_torch
  def 				lowercase_		(							self						:		List[str] )		->							Dict:
       SCREAMING_SNAKE_CASE__   =   pipeline(task='''fill-mask'''     ,       model='''sshleifer/tiny-distilroberta-base'''     ,       framework='''pt''' )
       SCREAMING_SNAKE_CASE__   =   None
       SCREAMING_SNAKE_CASE__   =   None
       self.run_pipeline_test(__lowerCamelCase     ,       [] )






  @require_tf
  def 				lowercase_		(							self						:		List[Any] )		->							int:
       SCREAMING_SNAKE_CASE__   =   pipeline(task='''fill-mask'''     ,       model='''sshleifer/tiny-distilroberta-base'''     ,       framework='''tf''' )
       SCREAMING_SNAKE_CASE__   =   None
       SCREAMING_SNAKE_CASE__   =   None
       self.run_pipeline_test(__lowerCamelCase     ,       [] )






  def 				lowercase_		(							self						:		str     ,       __lowerCamelCase						:		Any     ,       __lowerCamelCase						:		Dict     ,       __lowerCamelCase						:		Optional[Any] )		->							Union[str, Any]:
       if tokenizer is None or tokenizer.mask_token_id is None:
            self.skipTest('''The provided tokenizer has no mask token, (probably reformer or wav2vec2)''' )

       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   [
           f'''This is another {tokenizer.mask_token} test''',
       ]
       return fill_masker, examples






  def 				lowercase_		(							self						:		int     ,       __lowerCamelCase						:		Optional[int]     ,       __lowerCamelCase						:		Union[str, Any] )		->							Tuple:
       SCREAMING_SNAKE_CASE__   =   fill_masker.tokenizer
       SCREAMING_SNAKE_CASE__   =   fill_masker.model

       SCREAMING_SNAKE_CASE__   =   fill_masker(
           f'''This is a {tokenizer.mask_token}'''     ,       )
       self.assertEqual(
           __lowerCamelCase     ,       [
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   fill_masker([f'''This is a {tokenizer.mask_token}'''] )
       self.assertEqual(
           __lowerCamelCase     ,       [
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   fill_masker([f'''This is a {tokenizer.mask_token}''', f'''Another {tokenizer.mask_token} great test.'''] )
       self.assertEqual(
           __lowerCamelCase     ,       [
               [
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               ],
               [
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               ],
           ]     ,       )

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

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






  def 				lowercase_		(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		Optional[int]     ,       __lowerCamelCase						:		Union[str, Any] )		->							List[Any]:
       SCREAMING_SNAKE_CASE__   =   tokenizer.get_vocab()
       SCREAMING_SNAKE_CASE__   =   sorted(vocab.keys() )[:2]
       # Pipeline argument
       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase     ,       targets=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}''' )
       self.assertEqual(
           __lowerCamelCase     ,       [
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
           ]     ,       )
       SCREAMING_SNAKE_CASE__   =   {vocab[el] for el in targets}
       self.assertEqual({el['''token'''] for el in outputs}     ,       __lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   [tokenizer.decode([x] ) for x in target_ids]
       self.assertEqual({el['''token_str'''] for el in outputs}     ,       set(__lowerCamelCase ) )

       # Call argument
       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       targets=__lowerCamelCase )
       self.assertEqual(
           __lowerCamelCase     ,       [
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
           ]     ,       )
       SCREAMING_SNAKE_CASE__   =   {vocab[el] for el in targets}
       self.assertEqual({el['''token'''] for el in outputs}     ,       __lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   [tokenizer.decode([x] ) for x in target_ids]
       self.assertEqual({el['''token_str'''] for el in outputs}     ,       set(__lowerCamelCase ) )

       # Score equivalence
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       targets=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   [top_mask['''token_str'''] for top_mask in outputs]
       SCREAMING_SNAKE_CASE__   =   [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(__lowerCamelCase ) == set(__lowerCamelCase ):
            SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       targets=__lowerCamelCase )
            SCREAMING_SNAKE_CASE__   =   [top_mask['''score'''] for top_mask in unmasked_targets]
            self.assertEqual(nested_simplify(__lowerCamelCase )     ,       nested_simplify(__lowerCamelCase ) )

       # Raises with invalid
       with self.assertRaises(__lowerCamelCase ):
            SCREAMING_SNAKE_CASE__   =   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(__lowerCamelCase ):
                 SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       targets=[''''''] )
            with self.assertRaises(__lowerCamelCase ):
                 SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       targets='''''' )






  def 				lowercase_		(							self						:		List[str]     ,       __lowerCamelCase						:		Tuple     ,       __lowerCamelCase						:		Dict )		->							Tuple:
       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase     ,       top_k=2 )
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}''' )
       self.assertEqual(
           __lowerCamelCase     ,       [
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
           ]     ,       )

       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       top_k=2 )
       self.assertEqual(
           __lowerCamelCase     ,       [
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
           ]     ,       )
       self.assertEqual(nested_simplify(__lowerCamelCase )     ,       nested_simplify(__lowerCamelCase ) )






  def 				lowercase_		(							self						:		Optional[Any]     ,       __lowerCamelCase						:		Tuple     ,       __lowerCamelCase						:		Tuple )		->							Optional[Any]:
       SCREAMING_SNAKE_CASE__   =   tokenizer.get_vocab()
       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase )

       # top_k=2, ntargets=3
       SCREAMING_SNAKE_CASE__   =   sorted(vocab.keys() )[:3]
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''This is a {tokenizer.mask_token}'''     ,       top_k=2     ,       targets=__lowerCamelCase )

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






  def 				lowercase_		(							self						:		List[str]     ,       __lowerCamelCase						:		str     ,       __lowerCamelCase						:		Dict )		->							Any:
       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   tokenizer.get_vocab()
       # String duplicates + id duplicates
       SCREAMING_SNAKE_CASE__   =   sorted(vocab.keys() )[:3]
       SCREAMING_SNAKE_CASE__   =   [targets[0], targets[1], targets[0], targets[2], targets[1]]
       SCREAMING_SNAKE_CASE__   =   fill_masker(f'''My name is {tokenizer.mask_token}'''     ,       targets=__lowerCamelCase     ,       top_k=10 )

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







  def 				lowercase_		(							self						:		Optional[Any]     ,       __lowerCamelCase						:		Dict     ,       __lowerCamelCase						:		str )		->							List[Any]:
       SCREAMING_SNAKE_CASE__   =   FillMaskPipeline(model=__lowerCamelCase     ,       tokenizer=__lowerCamelCase )

       SCREAMING_SNAKE_CASE__   =   fill_masker(
           f'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}'''     ,       top_k=2 )
       self.assertEqual(
           __lowerCamelCase     ,       [
               [
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               ],
               [
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               ],
               [
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
                   {'''sequence''': ANY(__lowerCamelCase ), '''score''': ANY(__lowerCamelCase ), '''token''': ANY(__lowerCamelCase ), '''token_str''': ANY(__lowerCamelCase )},
               ],
           ]     ,       )





import comet  # From: unbabel-comet
import torch

import datasets


_SCREAMING_SNAKE_CASE					:  List[str]             =      datasets.logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE					:  Any             =      '''\
@inproceedings{rei-EtAl:2020:WMT,
   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},
   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},
   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},
   month          = {November},
   year           = {2020},
   address        = {Online},
   publisher      = {Association for Computational Linguistics},
   pages     = {909--918},
}
@inproceedings{rei-etal-2020-comet,
   title = "{COMET}: A Neural Framework for {MT} Evaluation",
   author = "Rei, Ricardo  and
      Stewart, Craig  and
      Farinha, Ana C  and
      Lavie, Alon",
   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",
   month = nov,
   year = "2020",
   address = "Online",
   publisher = "Association for Computational Linguistics",
   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",
   pages = "2685--2702",
}
'''

_SCREAMING_SNAKE_CASE					:  Optional[Any]             =      '''\
Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).
With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.

See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.
'''

_SCREAMING_SNAKE_CASE					:  str             =      '''
COMET score.

Args:

`sources` (list of str): Source sentences
`predictions` (list of str): candidate translations
`references` (list of str): reference translations
`cuda` (bool): If set to True, runs COMET using GPU
`show_progress` (bool): Shows progress
`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.

Returns:
    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.
    `scores`: List of scores.

Examples:

    >>> comet_metric = datasets.load_metric(\'comet\')
    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use
    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]
    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]
    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]
    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)
    >>> print([round(v, 2) for v in results["scores"]])
    [0.19, 0.92]
'''






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






  """simple docstring"""


  def 				lowercase_		(							self						:		List[Any] )		->							List[str]:
       return datasets.MetricInfo(
           description=_DESCRIPTION     ,       citation=_CITATION     ,       homepage='''https://unbabel.github.io/COMET/html/index.html'''     ,       inputs_description=_KWARGS_DESCRIPTION     ,       features=datasets.Features(
               {
                   '''sources''': datasets.Value('''string'''     ,       id='''sequence''' ),
                   '''predictions''': datasets.Value('''string'''     ,       id='''sequence''' ),
                   '''references''': datasets.Value('''string'''     ,       id='''sequence''' ),
               } )     ,       codebase_urls=['''https://github.com/Unbabel/COMET''']     ,       reference_urls=[
               '''https://github.com/Unbabel/COMET''',
               '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
               '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
           ]     ,       )






  def 				lowercase_		(							self						:		List[Any]     ,       __lowerCamelCase						:		Dict )		->							Tuple:
       if self.config_name == "default":
            SCREAMING_SNAKE_CASE__   =   comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da''' ) )
       else:
            SCREAMING_SNAKE_CASE__   =   comet.load_from_checkpoint(comet.download_model(self.config_name ) )







  def 				lowercase_		(							self						:		int     ,       __lowerCamelCase						:		List[str]     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		Dict=None     ,       __lowerCamelCase						:		Optional[int]=False )		->							str:
       if gpus is None:
            SCREAMING_SNAKE_CASE__   =   1 if torch.cuda.is_available() else 0
       SCREAMING_SNAKE_CASE__   =   {'''src''': sources, '''mt''': predictions, '''ref''': references}
       SCREAMING_SNAKE_CASE__   =   [dict(zip(__lowerCamelCase     ,       __lowerCamelCase ) ) for t in zip(*data.values() )]
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   self.scorer.predict(__lowerCamelCase     ,       gpus=__lowerCamelCase     ,       progress_bar=__lowerCamelCase )
       return {"mean_score": mean_score, "scores": scores}


