
"""simple docstring"""




import json
import os
import re
import unittest

from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__   ,					unittest.TestCase ):
       UpperCamelCase_   =		CodeGenTokenizer
       UpperCamelCase_   =		CodeGenTokenizerFast
       UpperCamelCase_   =		True
       UpperCamelCase_   =		{'''add_prefix_space''': True}
       UpperCamelCase_   =		False
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         super().setUp()

         # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
         _lowercase:			List[Any]       =     [
             '''l''',
             '''o''',
             '''w''',
             '''e''',
             '''r''',
             '''s''',
             '''t''',
             '''i''',
             '''d''',
             '''n''',
             '''\u0120''',
             '''\u0120l''',
             '''\u0120n''',
             '''\u0120lo''',
             '''\u0120low''',
             '''er''',
             '''\u0120lowest''',
             '''\u0120newer''',
             '''\u0120wider''',
             '''<unk>''',
             '''<|endoftext|>''',
         ]
         _lowercase:			Union[str, Any]       =     dict(zip(A_ ,				range(len(A_       )       )       )       )
         _lowercase:			Any       =     ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
         _lowercase:			Optional[int]       =     {'''unk_token''': '''<unk>'''}

         _lowercase:			int       =     os.path.join(self.tmpdirname ,				VOCAB_FILES_NAMES['''vocab_file''']       )
         _lowercase:			Tuple       =     os.path.join(self.tmpdirname ,				VOCAB_FILES_NAMES['''merges_file''']       )
         with open(self.vocab_file ,				'''w''' ,				encoding='''utf-8'''       ) as fp:
           fp.write(json.dumps(A_       ) + '''\n'''       )
         with open(self.merges_file ,				'''w''' ,				encoding='''utf-8'''       ) as fp:
           fp.write('''\n'''.join(A_       )       )
       def 							lowercase_							(     self ,				**A_       )     ->	Dict:





         """simple docstring"""




         kwargs.update(self.special_tokens_map       )
         return CodeGenTokenizer.from_pretrained(self.tmpdirname ,				**A_       )
       def 							lowercase_							(     self ,				**A_       )     ->	Any:





         """simple docstring"""




         kwargs.update(self.special_tokens_map       )
         return CodeGenTokenizerFast.from_pretrained(self.tmpdirname ,				**A_       )
       def 							lowercase_							(     self ,				A_       )     ->	Optional[int]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     '''lower newer'''
         _lowercase:			Any       =     '''lower newer'''
         return input_text, output_text
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			List[str]       =     CodeGenTokenizer(self.vocab_file ,				self.merges_file ,				**self.special_tokens_map       )
         _lowercase:			Union[str, Any]       =     '''lower newer'''
         _lowercase:			Union[str, Any]       =     ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
         _lowercase:			Optional[Any]       =     tokenizer.tokenize(A_ ,				add_prefix_space=A_       )
         self.assertListEqual(A_ ,				A_       )

         _lowercase:			Optional[Any]       =     tokens + [tokenizer.unk_token]
         _lowercase:			Any       =     [14, 15, 10, 9, 3, 2, 15, 19]
         self.assertListEqual(tokenizer.convert_tokens_to_ids(A_       ) ,				A_       )
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         if not self.test_rust_tokenizer:
           return

         _lowercase:			Any       =     self.get_tokenizer()
         _lowercase:			List[Any]       =     self.get_rust_tokenizer(add_prefix_space=A_       )

         _lowercase:			Tuple       =     '''lower newer'''

         # Testing tokenization
         _lowercase:			Optional[int]       =     tokenizer.tokenize(A_ ,				add_prefix_space=A_       )
         _lowercase:			Union[str, Any]       =     rust_tokenizer.tokenize(A_       )
         self.assertListEqual(A_ ,				A_       )

         # Testing conversion to ids without special tokens
         _lowercase:			Dict       =     tokenizer.encode(A_ ,				add_special_tokens=A_ ,				add_prefix_space=A_       )
         _lowercase:			str       =     rust_tokenizer.encode(A_ ,				add_special_tokens=A_       )
         self.assertListEqual(A_ ,				A_       )

         # Testing conversion to ids with special tokens
         _lowercase:			Optional[int]       =     self.get_rust_tokenizer(add_prefix_space=A_       )
         _lowercase:			str       =     tokenizer.encode(A_ ,				add_prefix_space=A_       )
         _lowercase:			Optional[int]       =     rust_tokenizer.encode(A_       )
         self.assertListEqual(A_ ,				A_       )

         # Testing the unknown token
         _lowercase:			str       =     tokens + [rust_tokenizer.unk_token]
         _lowercase:			List[str]       =     [14, 15, 10, 9, 3, 2, 15, 19]
         self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_       ) ,				A_       )
       def 							lowercase_							(     self ,				*A_ ,				**A_       )     ->	int:





         """simple docstring"""




         pass
       def 							lowercase_							(     self ,				A_=15       )     ->	List[Any]:





         """simple docstring"""




         for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
           with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''       ):
             _lowercase:			str       =     self.rust_tokenizer_class.from_pretrained(A_ ,				**A_       )

             # Simple input
             _lowercase:			Optional[Any]       =     '''This is a simple input'''
             _lowercase:			Tuple       =     ['''This is a simple input 1''', '''This is a simple input 2''']
             _lowercase:			Tuple       =     ('''This is a simple input''', '''This is a pair''')
             _lowercase:			Tuple       =     [
                 ('''This is a simple input 1''', '''This is a simple input 2'''),
                 ('''This is a simple pair 1''', '''This is a simple pair 2'''),
             ]

             # Simple input tests
             self.assertRaises(A_ ,				tokenizer_r.encode ,				A_ ,				max_length=A_ ,				padding='''max_length'''       )

             # Simple input
             self.assertRaises(A_ ,				tokenizer_r.encode_plus ,				A_ ,				max_length=A_ ,				padding='''max_length'''       )

             # Simple input
             self.assertRaises(
                 A_ ,				tokenizer_r.batch_encode_plus ,				A_ ,				max_length=A_ ,				padding='''max_length''' ,				)

             # Pair input
             self.assertRaises(A_ ,				tokenizer_r.encode ,				A_ ,				max_length=A_ ,				padding='''max_length'''       )

             # Pair input
             self.assertRaises(A_ ,				tokenizer_r.encode_plus ,				A_ ,				max_length=A_ ,				padding='''max_length'''       )

             # Pair input
             self.assertRaises(
                 A_ ,				tokenizer_r.batch_encode_plus ,				A_ ,				max_length=A_ ,				padding='''max_length''' ,				)
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     CodeGenTokenizer.from_pretrained(self.tmpdirname ,				pad_token='''<pad>'''       )

         # Simple input
         _lowercase:			Optional[int]       =     '''This is a simple input'''
         _lowercase:			Tuple       =     ['''This is a simple input looooooooong''', '''This is a simple input''']
         _lowercase:			Optional[int]       =     ('''This is a simple input''', '''This is a pair''')
         _lowercase:			str       =     [
             ('''This is a simple input loooooong''', '''This is a simple input'''),
             ('''This is a simple pair loooooong''', '''This is a simple pair'''),
         ]

         _lowercase:			str       =     tokenizer.pad_token_id

         _lowercase:			int       =     tokenizer(A_ ,				padding='''max_length''' ,				max_length=30 ,				return_tensors='''np'''       )
         _lowercase:			Any       =     tokenizer(A_ ,				padding=A_ ,				truncate=A_ ,				return_tensors='''np'''       )
         _lowercase:			List[Any]       =     tokenizer(*A_ ,				padding='''max_length''' ,				max_length=60 ,				return_tensors='''np'''       )
         _lowercase:			List[Any]       =     tokenizer(A_ ,				padding=A_ ,				truncate=A_ ,				return_tensors='''np'''       )

         # s
         # test single string max_length padding
         self.assertEqual(out_s['''input_ids'''].shape[-1] ,				30       )
         self.assertTrue(pad_token_id in out_s['''input_ids''']       )
         self.assertTrue(0 in out_s['''attention_mask''']       )

         # s2
         # test automatic padding
         self.assertEqual(out_sa['''input_ids'''].shape[-1] ,				33       )
         # long slice doesn't have padding
         self.assertFalse(pad_token_id in out_sa['''input_ids'''][0]       )
         self.assertFalse(0 in out_sa['''attention_mask'''][0]       )
         # short slice does have padding
         self.assertTrue(pad_token_id in out_sa['''input_ids'''][1]       )
         self.assertTrue(0 in out_sa['''attention_mask'''][1]       )

         # p
         # test single pair max_length padding
         self.assertEqual(out_p['''input_ids'''].shape[-1] ,				60       )
         self.assertTrue(pad_token_id in out_p['''input_ids''']       )
         self.assertTrue(0 in out_p['''attention_mask''']       )

         # p2
         # test automatic padding pair
         self.assertEqual(out_pa['''input_ids'''].shape[-1] ,				52       )
         # long slice pair doesn't have padding
         self.assertFalse(pad_token_id in out_pa['''input_ids'''][0]       )
         self.assertFalse(0 in out_pa['''attention_mask'''][0]       )
         # short slice pair does have padding
         self.assertTrue(pad_token_id in out_pa['''input_ids'''][1]       )
         self.assertTrue(0 in out_pa['''attention_mask'''][1]       )
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			List[str]       =     '''$$$'''
         _lowercase:			Optional[int]       =     CodeGenTokenizer.from_pretrained(self.tmpdirname ,				bos_token=A_ ,				add_bos_token=A_       )

         _lowercase:			int       =     '''This is a simple input'''
         _lowercase:			Optional[Any]       =     ['''This is a simple input 1''', '''This is a simple input 2''']

         _lowercase:			Dict       =     tokenizer.bos_token_id

         _lowercase:			str       =     tokenizer(A_       )
         _lowercase:			str       =     tokenizer(A_       )

         self.assertEqual(out_s.input_ids[0] ,				A_       )
         self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids       )       )

         _lowercase:			Tuple       =     tokenizer.decode(out_s.input_ids       )
         _lowercase:			Any       =     tokenizer.batch_decode(out_sa.input_ids       )

         self.assertEqual(decode_s.split()[0] ,				A_       )
         self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa       )       )
       @slow
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			str       =     CodeGenTokenizer.from_pretrained('''Salesforce/codegen-350M-mono'''       )

         _lowercase:			str       =     '''\nif len_a > len_b:\n    result = a\nelse:\n    result = b\n\n\n\n#'''
         _lowercase:			Dict       =     '''\nif len_a > len_b:      result = a\nelse:      result = b'''

         _lowercase:			List[Any]       =     tokenizer.encode(A_       )
         _lowercase:			Optional[int]       =     ['''^#''', re.escape('''<|endoftext|>'''       ), '''^\'\'\'''', '''^"""''', '''\n\n\n''']
         _lowercase:			Optional[Any]       =     tokenizer.decode(A_ ,				truncate_before_pattern=A_       )
         self.assertEqual(A_ ,				A_       )



       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         pass


"""simple docstring"""




import comet  # From: unbabel-comet
import torch

import datasets


A__   :					int							=   datasets.logging.get_logger(__name__)

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

A__   :					Union[str, Any]							=   '\\nCrosslingual 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).\nWith 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.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

A__   :					int							=   '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,					_KWARGS_DESCRIPTION )
class 			__magic_name__       (       datasets.Metric ):
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         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 ,				A_       )     ->	Dict:





         """simple docstring"""




         if self.config_name == "default":
           _lowercase:			str       =     comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
         else:
           _lowercase:			Optional[Any]       =     comet.load_from_checkpoint(comet.download_model(self.config_name       )       )



       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_=None ,				A_=False       )     ->	List[str]:





         """simple docstring"""




         if gpus is None:
           _lowercase:			Union[str, Any]       =     1 if torch.cuda.is_available() else 0
         _lowercase:			Any       =     {'''src''': sources, '''mt''': predictions, '''ref''': references}
         _lowercase:			int       =     [dict(zip(A_ ,				A_       )       ) for t in zip(*data.values()       )]
         _lowercase ,				_lowercase:			Tuple       =     self.scorer.predict(A_ ,				gpus=A_ ,				progress_bar=A_       )
         return {"mean_score": mean_score, "scores": scores}
