


'''simple docstring'''







import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
       if is_torch_available():
              import torch
       if is_tf_available():
              import tensorflow as tf

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


lowerCAmelCase     :  Optional[int]											=    logging.get_logger(__name__)

lowerCAmelCase     :  Union[str, Any]											=    {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase     :  Optional[Any]											=    {
    """vocab_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """Salesforce/codegen-350M-mono""": (
            """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"""
        ),
    },
}

lowerCAmelCase     :  List[str]											=    {
    """Salesforce/codegen-350M-mono""": 20_48,
}
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     __magic_name__           =     VOCAB_FILES_NAMES
     __magic_name__           =     PRETRAINED_VOCAB_FILES_MAP
     __magic_name__           =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __magic_name__           =     ["input_ids", "attention_mask"]
     __magic_name__           =     CodeGenTokenizer







     def __init__(			self   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__=False   ,						**snake_case__   ,						):

            '''simple docstring'''

            super().__init__(
                snake_case__   ,						snake_case__   ,						tokenizer_file=snake_case__   ,						unk_token=snake_case__   ,						bos_token=snake_case__   ,						eos_token=snake_case__   ,						add_prefix_space=snake_case__   ,						**snake_case__   ,						)

            if kwargs.pop('add_bos_token'   ,						snake_case__ ):
                   _lowerCAmelCase     :				Tuple       =							kwargs.pop('name_or_path'   ,						'' )
                   raise ValueError(
                       'Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'
                       'Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'
                       F'`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'
                       F'`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'
                       'This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'
                       ' so that the fast tokenizer works correctly.' )

            _lowerCAmelCase     :				List[str]       =							json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
            if pre_tok_state.get('add_prefix_space'   ,						snake_case__ ) != add_prefix_space:
                   _lowerCAmelCase     :				List[Any]       =							getattr(snake_case__   ,						pre_tok_state.pop('type' ) )
                   _lowerCAmelCase     :				Dict       =							add_prefix_space
                   _lowerCAmelCase     :				List[Any]       =							pre_tok_class(**snake_case__ )

            _lowerCAmelCase     :				Tuple       =							add_prefix_space







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )
            assert self.add_prefix_space or not is_split_into_words, (
                F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
                "to use it with pretokenized inputs."
            )

            return super()._batch_encode_plus(*snake_case__   ,						**snake_case__ )







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )

            assert self.add_prefix_space or not is_split_into_words, (
                F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
                "to use it with pretokenized inputs."
            )

            return super()._encode_plus(*snake_case__   ,						**snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = None ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self._tokenizer.model.save(snake_case__   ,						name=snake_case__ )
            return tuple(snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = False   ,						snake_case__ = None   ,						snake_case__ = None   ,						**snake_case__   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							super().decode(
                token_ids=snake_case__   ,						skip_special_tokens=snake_case__   ,						clean_up_tokenization_spaces=snake_case__   ,						**snake_case__   ,						)

            if truncate_before_pattern is not None and len(snake_case__ ) > 0:
                   _lowerCAmelCase     :				Optional[int]       =							self.truncate(snake_case__   ,						snake_case__ )

            return decoded_text







     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            def find_re(snake_case__   ,						snake_case__   ,						snake_case__ ):
                   _lowerCAmelCase     :				List[Any]       =							pattern.search(snake_case__   ,						snake_case__ )
                   return m.start() if m else -1

            _lowerCAmelCase     :				Any       =							[re.compile(snake_case__   ,						re.MULTILINE ) for pattern in truncate_before_pattern]

            _lowerCAmelCase     :				Dict       =							list(re.finditer('^print'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[int]       =							completion[: prints[1].start()]

            _lowerCAmelCase     :				Optional[int]       =							list(re.finditer('^def'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[Any]       =							completion[: defs[1].start()]

            _lowerCAmelCase     :				int       =							0

            _lowerCAmelCase     :				Tuple       =							[
                pos for pos in [find_re(snake_case__   ,						snake_case__   ,						snake_case__ ) for terminal in terminals] if pos != -1
            ]

            if len(snake_case__ ) > 0:
                   return completion[: min(snake_case__ )]
            else:
                   return completion





'''simple docstring'''







import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							tempfile.mkdtemp()
            _lowerCAmelCase     :				List[str]       =							5

            # Realm tok
            _lowerCAmelCase     :				str       =							[
                '[UNK]',
                '[CLS]',
                '[SEP]',
                '[PAD]',
                '[MASK]',
                'test',
                'question',
                'this',
                'is',
                'the',
                'first',
                'second',
                'third',
                'fourth',
                'fifth',
                'record',
                'want',
                '##want',
                '##ed',
                'wa',
                'un',
                'runn',
                '##ing',
                ',',
                'low',
                'lowest',
            ]
            _lowerCAmelCase     :				Union[str, Any]       =							os.path.join(self.tmpdirname   ,						'realm_tokenizer' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )
            _lowerCAmelCase     :				Dict       =							os.path.join(snake_case__   ,						VOCAB_FILES_NAMES['vocab_file'] )
            with open(self.vocab_file   ,						'w'   ,						encoding='utf-8' ) as vocab_writer:
                   vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )

            _lowerCAmelCase     :				List[str]       =							os.path.join(self.tmpdirname   ,						'realm_block_records' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_tokenizer' ) )







     def a						(			self ):

            '''simple docstring'''

            shutil.rmtree(self.tmpdirname )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							RealmConfig(num_block_records=self.num_block_records )
            return config







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							Dataset.from_dict(
                {
                    'id': ['0', '1'],
                    'question': ['foo', 'bar'],
                    'answers': [['Foo', 'Bar'], ['Bar']],
                } )
            return dataset







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							np.array(
                [
                    b'This is the first record',
                    b'This is the second record',
                    b'This is the third record',
                    b'This is the fourth record',
                    b'This is the fifth record',
                    b'This is a longer longer longer record',
                ]   ,						dtype=snake_case__   ,						)
            return block_records







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							RealmRetriever(
                block_records=self.get_dummy_block_records()   ,						tokenizer=self.get_tokenizer()   ,						)
            return retriever







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							self.get_config()
            _lowerCAmelCase     :				List[Any]       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				Any       =							retriever.tokenizer

            _lowerCAmelCase     :				Tuple       =							np.array([0, 3]   ,						dtype='long' )
            _lowerCAmelCase     :				Dict       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				int       =							tokenizer(
                ['the fourth']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Tuple       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Union[str, Any]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(concat_inputs.input_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.attention_mask.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.token_type_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.special_tokens_mask.shape   ,						(2, 10) )
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]']   ,						)
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]']   ,						)







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.get_config()
            _lowerCAmelCase     :				int       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				List[str]       =							retriever.tokenizer

            _lowerCAmelCase     :				List[Any]       =							np.array([0, 3, 5]   ,						dtype='long' )
            _lowerCAmelCase     :				str       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				Union[str, Any]       =							tokenizer(
                ['the fourth', 'longer longer']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Optional[int]       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				List[str]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual([False, True, True]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]   ,						snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self.get_dummy_retriever()
            retriever.save_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )

            # Test local path
            _lowerCAmelCase     :				Union[str, Any]       =							retriever.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )
            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

            # Test mocked remote path
            with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download:
                   _lowerCAmelCase     :				Any       =							os.path.join(
                       os.path.join(self.tmpdirname   ,						'realm_block_records' )   ,						_REALM_BLOCK_RECORDS_FILENAME )
                   _lowerCAmelCase     :				str       =							RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' )

            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

