
"""simple docstring"""


import json
import os
import unittest

from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast
from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class  lowerCAmelCase_ (					_lowercase						,    unittest.TestCase			):



						'''simple docstring'''


						_lowerCamelCase:			Tuple					=			GPTaTokenizer
						_lowerCamelCase:			Tuple					=			GPTaTokenizerFast
						_lowerCamelCase:			str					=			True
						_lowerCamelCase:			Any					=			{'''add_prefix_space''': True}
						_lowerCamelCase:			List[Any]					=			False


						def   _SCREAMING_SNAKE_CASE					(       self   :					Dict					)   ->      List[Any]:
							super().setUp()

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

							A        =      os.path.join(self.tmpdirname     ,VOCAB_FILES_NAMES['vocab_file']					)
							A        =      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   _SCREAMING_SNAKE_CASE					(       self   :					Optional[Any]     ,**A_   :					Tuple					)   ->      Any:
							kwargs.update(self.special_tokens_map					)
							return GPTaTokenizer.from_pretrained(self.tmpdirname     ,**A_					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					str     ,**A_   :					List[str]					)   ->      List[str]:
							kwargs.update(self.special_tokens_map					)
							return GPTaTokenizerFast.from_pretrained(self.tmpdirname     ,**A_					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					List[str]     ,A_   :					List[Any]					)   ->      Union[str, Any]:
							A        =      'lower newer'
							A        =      'lower newer'
							return input_text, output_text


						def   _SCREAMING_SNAKE_CASE					(       self   :					List[Any]					)   ->      List[Any]:
							A        =      GPTaTokenizer(self.vocab_file     ,self.merges_file     ,**self.special_tokens_map					)
							A        =      'lower newer'
							A        =      ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er']
							A        =      tokenizer.tokenize(A_     ,add_prefix_space=A_					)
							self.assertListEqual(A_     ,A_					)

							A        =      tokens + [tokenizer.unk_token]
							A        =      [14, 15, 10, 9, 3, 2, 15, 19]
							self.assertListEqual(tokenizer.convert_tokens_to_ids(A_					)     ,A_					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					int					)   ->      Optional[Any]:
							if not self.test_rust_tokenizer:
								return

							A        =      self.get_tokenizer()
							A        =      self.get_rust_tokenizer(add_prefix_space=A_					)

							A        =      'lower newer'

							# Testing tokenization
							A        =      tokenizer.tokenize(A_     ,add_prefix_space=A_					)
							A        =      rust_tokenizer.tokenize(A_					)
							self.assertListEqual(A_     ,A_					)

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

							# Testing conversion to ids with special tokens
							A        =      self.get_rust_tokenizer(add_prefix_space=A_					)
							A        =      tokenizer.encode(A_     ,add_prefix_space=A_					)
							A        =      rust_tokenizer.encode(A_					)
							self.assertListEqual(A_     ,A_					)

							# Testing the unknown token
							A        =      tokens + [rust_tokenizer.unk_token]
							A        =      [14, 15, 10, 9, 3, 2, 15, 19]
							self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_					)     ,A_					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Union[str, Any]     ,*A_   :					Any     ,**A_   :					Dict					)   ->      Any:
							# It's very difficult to mix/test pretokenization with byte-level
							# And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string)
							pass


						def   _SCREAMING_SNAKE_CASE					(       self   :					List[Any]     ,A_   :					List[Any]=15					)   ->      Union[str, Any]:
							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
								with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'					):
									A        =      self.rust_tokenizer_class.from_pretrained(A_     ,**A_					)

									# Simple input
									A        =      'This is a simple input'
									A        =      ['This is a simple input 1', 'This is a simple input 2']
									A        =      ('This is a simple input', 'This is a pair')
									A        =      [
									    ('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   _SCREAMING_SNAKE_CASE					(       self   :					str					)   ->      List[Any]:
							A        =      GPTaTokenizer.from_pretrained(self.tmpdirname     ,pad_token='<pad>'					)

							# Simple input
							A        =      'This is a simple input'
							A        =      ['This is a simple input looooooooong', 'This is a simple input']
							A        =      ('This is a simple input', 'This is a pair')
							A        =      [
							    ('This is a simple input loooooong', 'This is a simple input'),
							    ('This is a simple pair loooooong', 'This is a simple pair'),
							]

							A        =      tokenizer.pad_token_id

							A        =      tokenizer(A_     ,padding='max_length'     ,max_length=30     ,return_tensors='np'					)
							A        =      tokenizer(A_     ,padding=A_     ,truncate=A_     ,return_tensors='np'					)
							A        =      tokenizer(*A_     ,padding='max_length'     ,max_length=60     ,return_tensors='np'					)
							A        =      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   _SCREAMING_SNAKE_CASE					(       self   :					Union[str, Any]					)   ->      Optional[int]:
							A        =      '$$$'
							A        =      GPTaTokenizer.from_pretrained(self.tmpdirname     ,bos_token=A_     ,add_bos_token=A_					)

							A        =      'This is a simple input'
							A        =      ['This is a simple input 1', 'This is a simple input 2']

							A        =      tokenizer.bos_token_id

							A        =      tokenizer(A_					)
							A        =      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					)					)

							A        =      tokenizer.decode(out_s.input_ids					)
							A        =      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					)					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Union[str, Any]					)   ->      int:
							pass




						def   _SCREAMING_SNAKE_CASE					(       self   :					int					)   ->      Union[str, Any]:
							# TODO: change to self.get_tokenizers() when the fast version is implemented
							A        =      [self.get_tokenizer(do_lower_case=A_     ,add_bos_token=A_					)]
							for tokenizer in tokenizers:
								with self.subTest(F'{tokenizer.__class__.__name__}'					):
									A        =      'Encode this.'
									A        =      'This one too please.'
									A        =      tokenizer.encode(A_     ,add_special_tokens=A_					)
									encoded_sequence += tokenizer.encode(A_     ,add_special_tokens=A_					)
									A        =      tokenizer.encode_plus(
									    A_     ,A_     ,add_special_tokens=A_     ,return_special_tokens_mask=A_     ,)
									A        =      encoded_sequence_dict['input_ids']
									A        =      encoded_sequence_dict['special_tokens_mask']
									self.assertEqual(len(A_					)     ,len(A_					)					)

									A        =      [
									    (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_					)
									]
									A        =      [x for x in filtered_sequence if x is not None]
									self.assertEqual(A_     ,A_					)







@require_tokenizers
class  lowerCAmelCase_ (					unittest.TestCase			):



						'''simple docstring'''


						def   _SCREAMING_SNAKE_CASE					(       self   :					Any					)   ->      str:
							# More context:
							# https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1
							# https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519
							# https://github.com/huggingface/transformers/pull/17088#discussion_r871246439

							A        =      AutoTokenizer.from_pretrained('facebook/opt-350m'     ,from_slow=A_					)
							A        =      'A photo of a cat'

							A        =      tokenizer.encode(
							    A_     ,)
							self.assertEqual(A_     ,[2, 250, 1345, 9, 10, 4758]					)
							tokenizer.save_pretrained('test_opt'					)

							A        =      AutoTokenizer.from_pretrained('./test_opt'					)
							A        =      tokenizer.encode(
							    A_     ,)
							self.assertEqual(A_     ,[2, 250, 1345, 9, 10, 4758]					)


						def   _SCREAMING_SNAKE_CASE					(       self   :					Optional[int]					)   ->      Optional[Any]:
							A        =      AutoTokenizer.from_pretrained('facebook/opt-350m'     ,use_slow=A_					)
							A        =      'A photo of a cat'

							A        =      tokenizer.encode(
							    A_     ,)
							# Same as above
							self.assertEqual(A_     ,[2, 250, 1345, 9, 10, 4758]					)




						@unittest.skip('This test is failing because of a bug in the fast tokenizer'					)
						def   _SCREAMING_SNAKE_CASE					(       self   :					Dict					)   ->      Dict:
							A        =      AutoTokenizer.from_pretrained('facebook/opt-350m'     ,from_slow=A_					)

							A        =      'bos'
							A        =      tokenizer.get_vocab()['bos']

							A        =      'A photo of a cat'
							A        =      tokenizer.encode(
							    A_     ,)
							# We changed the bos token
							self.assertEqual(A_     ,[3_1957, 250, 1345, 9, 10, 4758]					)
							tokenizer.save_pretrained('./tok'					)
							A        =      AutoTokenizer.from_pretrained('./tok'					)
							self.assertTrue(tokenizer.is_fast					)
							A        =      tokenizer.encode(
							    A_     ,)
							self.assertEqual(A_     ,[3_1957, 250, 1345, 9, 10, 4758]					)







"""simple docstring"""






import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
UpperCAmelCase_   : Optional[int]   			= """src/transformers"""
UpperCAmelCase_   : Tuple   			= """docs/source/en"""
UpperCAmelCase_   : Optional[Any]   			= """."""



def 					_A			(__a    ,				__a    ,				__a							) ->       Dict:
    """simple docstring"""






    with open(__a    ,				'''r'''    ,				encoding='''utf-8'''    ,				newline='''\n'''							) as f:
        SCREAMING_SNAKE_CASE_      :  Dict    						=		f.readlines()
    # Find the start prompt.
    SCREAMING_SNAKE_CASE_      :  List[Any]    						=		0
    while not lines[start_index].startswith(__a							):
        start_index += 1
    start_index += 1

    SCREAMING_SNAKE_CASE_      :  Tuple    						=		start_index
    while not lines[end_index].startswith(__a							):
        end_index += 1
    end_index -= 1

    while len(lines[start_index]							) <= 1:
        start_index += 1
    while len(lines[end_index]							) <= 1:
        end_index -= 1
    end_index += 1
    return "".join(lines[start_index:end_index]							), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
UpperCAmelCase_   : Optional[Any]   			= """Model|Encoder|Decoder|ForConditionalGeneration"""
# Regexes that match TF/Flax/PT model names.
UpperCAmelCase_   : int   			= re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
UpperCAmelCase_   : Dict   			= re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
UpperCAmelCase_   : int   			= re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")


# This is to make sure the transformers module imported is the one in the repo.
UpperCAmelCase_   : Optional[int]   			= direct_transformers_import(TRANSFORMERS_PATH)



def 					_A			(__a							) ->       int:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  Dict    						=		re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''    ,				__a							)
    return [m.group(0							) for m in matches]



def 					_A			(__a    ,				__a							) ->       int:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  List[Any]    						=		2 if text == '''✅''' or text == '''❌''' else len(__a							)
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		(width - text_length) // 2
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		width - text_length - left_indent
    return " " * left_indent + text + " " * right_indent



def 					_A			() ->       int:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		{
        name: config_maping_names[code]
        for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
        if code in config_maping_names
    }
    SCREAMING_SNAKE_CASE_      :  List[Any]    						=		{name: config.replace('''Config'''    ,				''''''							) for name, config in model_name_to_config.items()}

    # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
    SCREAMING_SNAKE_CASE_      :  List[str]    						=		collections.defaultdict(__a							)
    SCREAMING_SNAKE_CASE_      :  int    						=		collections.defaultdict(__a							)
    SCREAMING_SNAKE_CASE_      :  List[str]    						=		collections.defaultdict(__a							)
    SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		collections.defaultdict(__a							)
    SCREAMING_SNAKE_CASE_      :  int    						=		collections.defaultdict(__a							)

    # Let's lookup through all transformers object (once).
    for attr_name in dir(__a							):
        SCREAMING_SNAKE_CASE_      :  Any    						=		None
        if attr_name.endswith('''Tokenizer'''							):
            SCREAMING_SNAKE_CASE_      :  Dict    						=		slow_tokenizers
            SCREAMING_SNAKE_CASE_      :  Dict    						=		attr_name[:-9]
        elif attr_name.endswith('''TokenizerFast'''							):
            SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		fast_tokenizers
            SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		attr_name[:-13]
        elif _re_tf_models.match(__a							) is not None:
            SCREAMING_SNAKE_CASE_      :  int    						=		tf_models
            SCREAMING_SNAKE_CASE_      :  Dict    						=		_re_tf_models.match(__a							).groups()[0]
        elif _re_flax_models.match(__a							) is not None:
            SCREAMING_SNAKE_CASE_      :  Any    						=		flax_models
            SCREAMING_SNAKE_CASE_      :  Tuple    						=		_re_flax_models.match(__a							).groups()[0]
        elif _re_pt_models.match(__a							) is not None:
            SCREAMING_SNAKE_CASE_      :  str    						=		pt_models
            SCREAMING_SNAKE_CASE_      :  int    						=		_re_pt_models.match(__a							).groups()[0]

        if lookup_dict is not None:
            while len(__a							) > 0:
                if attr_name in model_name_to_prefix.values():
                    SCREAMING_SNAKE_CASE_      :  List[str]    						=		True
                    break
                # Try again after removing the last word in the name
                SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		''''''.join(camel_case_split(__a							)[:-1]							)

    # Let's build that table!
    SCREAMING_SNAKE_CASE_      :  Any    						=		list(model_name_to_config.keys()							)
    model_names.sort(key=str.lower							)
    SCREAMING_SNAKE_CASE_      :  Any    						=		['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support''']
    # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
    SCREAMING_SNAKE_CASE_      :  List[str]    						=		[len(__a							) + 2 for c in columns]
    SCREAMING_SNAKE_CASE_      :  str    						=		max([len(__a							) for name in model_names]							) + 2

    # Build the table per se
    SCREAMING_SNAKE_CASE_      :  List[Any]    						=		'''|''' + '''|'''.join([_center_text(__a    ,				__a							) for c, w in zip(__a    ,				__a							)]							) + '''|\n'''
    # Use ":-----:" format to center-aligned table cell texts
    table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths]							) + "|\n"

    SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		{True: '''✅''', False: '''❌'''}
    for name in model_names:
        SCREAMING_SNAKE_CASE_      :  str    						=		model_name_to_prefix[name]
        SCREAMING_SNAKE_CASE_      :  int    						=		[
            name,
            check[slow_tokenizers[prefix]],
            check[fast_tokenizers[prefix]],
            check[pt_models[prefix]],
            check[tf_models[prefix]],
            check[flax_models[prefix]],
        ]
        table += "|" + "|".join([_center_text(__a    ,				__a							) for l, w in zip(__a    ,				__a							)]							) + "|\n"
    return table



def 					_A			(__a=False							) ->       List[str]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  List[Any]    						=		_find_text_in_file(
        filename=os.path.join(__a    ,				'''index.md'''							)    ,				start_prompt='''<!--This table is updated automatically from the auto modules'''    ,				end_prompt='''<!-- End table-->'''    ,				)
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		get_model_table_from_auto_modules()

    if current_table != new_table:
        if overwrite:
            with open(os.path.join(__a    ,				'''index.md'''							)    ,				'''w'''    ,				encoding='''utf-8'''    ,				newline='''\n'''							) as f:
                f.writelines(lines[:start_index] + [new_table] + lines[end_index:]							)
        else:
            raise ValueError(
                '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.'''							)


if __name__ == "__main__":
  UpperCAmelCase_   : Union[str, Any]   			= argparse.ArgumentParser()
  parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
  UpperCAmelCase_   : Any   			= parser.parse_args()

  check_model_table(args.fix_and_overwrite)


