



"""simple docstring"""

import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase__    :  List[Any]							    =	logging.get_logger(__name__)

lowercase__    :  str							    =	'''▁'''

lowercase__    :  List[str]							    =	{
    '''vocab_file''': '''vocab.json''',
    '''spm_file''': '''sentencepiece.bpe.model''',
}

lowercase__    :  Any							    =	{
    '''vocab_file''': {
        '''facebook/s2t-small-librispeech-asr''': (
            '''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json'''
        ),
    },
    '''spm_file''': {
        '''facebook/s2t-small-librispeech-asr''': (
            '''https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model'''
        )
    },
}

lowercase__    :  List[str]							    =	{
    '''facebook/s2t-small-librispeech-asr''': 10_24,
}

lowercase__    :  Union[str, Any]							    =	['''pt''', '''fr''', '''ru''', '''nl''', '''ro''', '''it''', '''es''', '''de''']

lowercase__    :  int							    =	{'''mustc''': MUSTC_LANGS}




class        _UpperCAmelCase       (			lowerCAmelCase__):
 _lowerCAmelCase   :			str							=		VOCAB_FILES_NAMES
 _lowerCAmelCase   :			Any							=		PRETRAINED_VOCAB_FILES_MAP
 _lowerCAmelCase   :			str							=		MAX_MODEL_INPUT_SIZES
 _lowerCAmelCase   :			Any							=		["""input_ids""", """attention_mask"""]

 _lowerCAmelCase   :			List[int]							=		[]

 def __init__(     self		:       List[str]  ,     lowercase_		:       List[Any]  ,     lowercase_		:       Tuple  ,     lowercase_		:       List[str]="<s>"  ,     lowercase_		:       Optional[int]="</s>"  ,     lowercase_		:       Optional[Any]="<pad>"  ,     lowercase_		:       List[str]="<unk>"  ,     lowercase_		:       Tuple=False  ,     lowercase_		:       Any=False  ,     lowercase_		:       int=None  ,     lowercase_		:       List[Any]=None  ,     lowercase_		:       Optional[Dict[str, Any]] = None  ,     **lowercase_		:       Union[str, Any]  ,     ):
     snake_case_ :     str				=	{} if sp_model_kwargs is None else sp_model_kwargs

     super().__init__(
         bos_token=lowercase_  ,     eos_token=lowercase_  ,     unk_token=lowercase_  ,     pad_token=lowercase_  ,     do_upper_case=lowercase_  ,     do_lower_case=lowercase_  ,     tgt_lang=lowercase_  ,     lang_codes=lowercase_  ,     sp_model_kwargs=self.sp_model_kwargs  ,     **lowercase_  ,     )
     snake_case_ :     Dict				=	do_upper_case
     snake_case_ :     Tuple				=	do_lower_case

     snake_case_ :     List[Any]				=	load_json(lowercase_				)
     snake_case_ :     int				=	{v: k for k, v in self.encoder.items()}
     snake_case_ :     Optional[Any]				=	spm_file
     snake_case_ :     List[Any]				=	load_spm(lowercase_  ,     self.sp_model_kwargs				)

     if lang_codes is not None:
         snake_case_ :     List[str]				=	lang_codes
         snake_case_ :     Union[str, Any]				=	LANGUAGES[lang_codes]
         snake_case_ :     Dict				=	[f"<lang:{lang}>" for lang in self.langs]
         snake_case_ :     Dict				=	{lang: self.sp_model.PieceToId(f"<lang:{lang}>"				) for lang in self.langs}

         snake_case_ :     Union[str, Any]				=	self.lang_tokens
         snake_case_ :     Optional[int]				=	tgt_lang if tgt_lang is not None else self.langs[0]

         self.set_tgt_lang_special_tokens(self._tgt_lang				)
     else:
         snake_case_ :     List[str]				=	{}

 @property
 def 						_snake_case					(     self		:       Union[str, Any]				):
     return len(self.encoder				)

 @property
 def 						_snake_case					(     self		:       Dict				):
     return self._tgt_lang

 @tgt_lang.setter
 def 						_snake_case					(     self		:       Any  ,     lowercase_		:       Optional[Any]				):
     snake_case_ :     Optional[Any]				=	new_tgt_lang
     self.set_tgt_lang_special_tokens(lowercase_				)

 def 						_snake_case					(     self		:       Union[str, Any]  ,     lowercase_		:       str				):
     snake_case_ :     Any				=	self.lang_code_to_id[tgt_lang]
     snake_case_ :     Union[str, Any]				=	[lang_code_id]

 def 						_snake_case					(     self		:       List[str]  ,     lowercase_		:       str				):
     return self.sp_model.encode(lowercase_  ,     out_type=lowercase_				)

 def 						_snake_case					(     self		:       Union[str, Any]  ,     lowercase_		:       Dict				):
     return self.encoder.get(lowercase_  ,     self.encoder[self.unk_token]				)

 def 						_snake_case					(     self		:       str  ,     lowercase_		:       int				):
     return self.decoder.get(lowercase_  ,     self.unk_token				)

 def 						_snake_case					(     self		:       List[Any]  ,     lowercase_		:       List[str]				):
     snake_case_ :     str				=	[]
     snake_case_ :     List[str]				=	''''''
     for token in tokens:
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
             snake_case_ :     int				=	self.sp_model.decode(lowercase_				)
             out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
             snake_case_ :     Union[str, Any]				=	[]
         else:
             current_sub_tokens.append(lowercase_				)
     snake_case_ :     Dict				=	self.sp_model.decode(lowercase_				)
     out_string += decoded.upper() if self.do_upper_case else decoded
     return out_string.strip()

 def 						_snake_case					(     self		:       str  ,     lowercase_		:       Any  ,     lowercase_		:       List[str]=None				):
     if token_ids_a is None:
         return self.prefix_tokens + token_ids_a + [self.eos_token_id]
     # We don't expect to process pairs, but leave the pair logic for API consistency
     return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]

 def 						_snake_case					(     self		:       Optional[int]  ,     lowercase_		:       List[int]  ,     lowercase_		:       Optional[List[int]] = None  ,     lowercase_		:       bool = False				):

     if already_has_special_tokens:
         return super().get_special_tokens_mask(
             token_ids_a=lowercase_  ,     token_ids_a=lowercase_  ,     already_has_special_tokens=lowercase_				)

     snake_case_ :     str				=	[1] * len(self.prefix_tokens				)
     snake_case_ :     List[str]				=	[1]
     if token_ids_a is None:
         return prefix_ones + ([0] * len(lowercase_				)) + suffix_ones
     return prefix_ones + ([0] * len(lowercase_				)) + ([0] * len(lowercase_				)) + suffix_ones

 def 						_snake_case					(     self		:       Tuple				):
     snake_case_ :     Optional[int]				=	self.encoder.copy()
     vocab.update(self.added_tokens_encoder				)
     return vocab

 def __getstate__(     self		:       Union[str, Any]				):
     snake_case_ :     Tuple				=	self.__dict__.copy()
     snake_case_ :     Optional[Any]				=	None
     return state

 def __setstate__(     self		:       List[str]  ,     lowercase_		:       Dict				):
     snake_case_ :     str				=	d

     # for backward compatibility
     if not hasattr(self  ,     '''sp_model_kwargs'''				):
         snake_case_ :     List[str]				=	{}

     snake_case_ :     Union[str, Any]				=	load_spm(self.spm_file  ,     self.sp_model_kwargs				)






 def 						_snake_case					(     self		:       Optional[Any]  ,     lowercase_		:       str  ,     lowercase_		:       Optional[str] = None				):
     snake_case_ :     List[str]				=	Path(lowercase_				)
     assert save_dir.is_dir(), f"{save_directory} should be a directory"
     snake_case_ :     str				=	save_dir / (
         (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file''']
     )
     snake_case_ :     List[str]				=	save_dir / (
         (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file''']
     )

     save_json(self.encoder  ,     lowercase_				)

     if os.path.abspath(self.spm_file				) != os.path.abspath(lowercase_				) and os.path.isfile(self.spm_file				):
         copyfile(self.spm_file  ,     lowercase_				)
     elif not os.path.isfile(self.spm_file				):
         with open(lowercase_  ,     '''wb'''				) as fi:
             snake_case_ :     str				=	self.sp_model.serialized_model_proto()
             fi.write(lowercase_				)

     return (str(lowercase_				), str(lowercase_				))





def __lowercase			(							_a		,			_a    ):
    snake_case_ :     int				=	sentencepiece.SentencePieceProcessor(**_a    )
    spm.Load(str(_a    )    )
    return spm




def __lowercase			(							_a    ):
    with open(_a		,			'''r'''    ) as f:
        return json.load(_a    )






def __lowercase			(							_a		,			_a    ):
    with open(_a		,			'''w'''    ) as f:
        json.dump(_a		,			_a		,			indent=2    )










"""simple docstring"""

import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
         OpenAIGPTConfig,
         OpenAIGPTDoubleHeadsModel,
         OpenAIGPTForSequenceClassification,
         OpenAIGPTLMHeadModel,
         OpenAIGPTModel,
     )




class        _UpperCAmelCase       :

 def __init__(     self		:       Union[str, Any]  ,     lowercase_		:       List[Any]  ,     lowercase_		:       int=13  ,     lowercase_		:       Optional[int]=7  ,     lowercase_		:       Any=True  ,     lowercase_		:       Dict=True  ,     lowercase_		:       Dict=True  ,     lowercase_		:       Optional[Any]=99  ,     lowercase_		:       Union[str, Any]=32  ,     lowercase_		:       str=5  ,     lowercase_		:       Union[str, Any]=4  ,     lowercase_		:       Any=37  ,     lowercase_		:       Tuple="gelu"  ,     lowercase_		:       Dict=0.1  ,     lowercase_		:       Tuple=0.1  ,     lowercase_		:       Optional[int]=512  ,     lowercase_		:       Optional[Any]=16  ,     lowercase_		:       Optional[Any]=2  ,     lowercase_		:       Optional[Any]=0.02  ,     lowercase_		:       List[Any]=3  ,     lowercase_		:       Union[str, Any]=4  ,     lowercase_		:       List[Any]=None  ,     ):
     snake_case_ :     Any				=	parent
     snake_case_ :     List[str]				=	batch_size
     snake_case_ :     List[Any]				=	seq_length
     snake_case_ :     Optional[int]				=	is_training
     snake_case_ :     Union[str, Any]				=	use_token_type_ids
     snake_case_ :     Optional[Any]				=	use_labels
     snake_case_ :     Union[str, Any]				=	vocab_size
     snake_case_ :     Any				=	hidden_size
     snake_case_ :     List[Any]				=	num_hidden_layers
     snake_case_ :     Any				=	num_attention_heads
     snake_case_ :     Dict				=	intermediate_size
     snake_case_ :     Union[str, Any]				=	hidden_act
     snake_case_ :     Optional[int]				=	hidden_dropout_prob
     snake_case_ :     Optional[Any]				=	attention_probs_dropout_prob
     snake_case_ :     Tuple				=	max_position_embeddings
     snake_case_ :     int				=	type_vocab_size
     snake_case_ :     Tuple				=	type_sequence_label_size
     snake_case_ :     str				=	initializer_range
     snake_case_ :     Tuple				=	num_labels
     snake_case_ :     str				=	num_choices
     snake_case_ :     Any				=	scope
     snake_case_ :     Dict				=	self.vocab_size - 1

 def 						_snake_case					(     self		:       int				):
     snake_case_ :     Optional[Any]				=	ids_tensor([self.batch_size, self.seq_length]  ,     self.vocab_size				)

     snake_case_ :     Optional[Any]				=	None
     if self.use_token_type_ids:
         snake_case_ :     Tuple				=	ids_tensor([self.batch_size, self.seq_length]  ,     self.type_vocab_size				)

     snake_case_ :     str				=	None
     snake_case_ :     Dict				=	None
     snake_case_ :     str				=	None
     if self.use_labels:
         snake_case_ :     Optional[int]				=	ids_tensor([self.batch_size]  ,     self.type_sequence_label_size				)
         snake_case_ :     List[Any]				=	ids_tensor([self.batch_size, self.seq_length]  ,     self.num_labels				)
         snake_case_ :     Tuple				=	ids_tensor([self.batch_size]  ,     self.num_choices				)

     snake_case_ :     int				=	OpenAIGPTConfig(
         vocab_size=self.vocab_size  ,     n_embd=self.hidden_size  ,     n_layer=self.num_hidden_layers  ,     n_head=self.num_attention_heads  ,     n_positions=self.max_position_embeddings  ,     pad_token_id=self.pad_token_id  ,     )

     snake_case_ :     Any				=	ids_tensor([self.num_hidden_layers, self.num_attention_heads]  ,     2				)

     return (
         config,
         input_ids,
         head_mask,
         token_type_ids,
         sequence_labels,
         token_labels,
         choice_labels,
     )

 def 						_snake_case					(     self		:       Tuple  ,     lowercase_		:       Any  ,     lowercase_		:       Union[str, Any]  ,     lowercase_		:       str  ,     lowercase_		:       Dict  ,     *lowercase_		:       Dict				):
     snake_case_ :     List[Any]				=	OpenAIGPTModel(config=lowercase_				)
     model.to(lowercase_				)
     model.eval()

     snake_case_ :     Any				=	model(lowercase_  ,     token_type_ids=lowercase_  ,     head_mask=lowercase_				)
     snake_case_ :     Optional[Any]				=	model(lowercase_  ,     token_type_ids=lowercase_				)
     snake_case_ :     Optional[Any]				=	model(lowercase_				)

     self.parent.assertEqual(result.last_hidden_state.shape  ,     (self.batch_size, self.seq_length, self.hidden_size)				)

 def 						_snake_case					(     self		:       Tuple  ,     lowercase_		:       Dict  ,     lowercase_		:       str  ,     lowercase_		:       Optional[Any]  ,     lowercase_		:       List[Any]  ,     *lowercase_		:       Optional[Any]				):
     snake_case_ :     Union[str, Any]				=	OpenAIGPTLMHeadModel(lowercase_				)
     model.to(lowercase_				)
     model.eval()

     snake_case_ :     Union[str, Any]				=	model(lowercase_  ,     token_type_ids=lowercase_  ,     labels=lowercase_				)
     self.parent.assertEqual(result.loss.shape  ,     ()				)
     self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.seq_length, self.vocab_size)				)

 def 						_snake_case					(     self		:       List[str]  ,     lowercase_		:       Dict  ,     lowercase_		:       List[str]  ,     lowercase_		:       Any  ,     lowercase_		:       Dict  ,     *lowercase_		:       Union[str, Any]				):
     snake_case_ :     Tuple				=	OpenAIGPTDoubleHeadsModel(lowercase_				)
     model.to(lowercase_				)
     model.eval()

     snake_case_ :     Dict				=	model(lowercase_  ,     token_type_ids=lowercase_  ,     labels=lowercase_				)
     self.parent.assertEqual(result.loss.shape  ,     ()				)
     self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.seq_length, self.vocab_size)				)

 def 						_snake_case					(     self		:       Any  ,     lowercase_		:       str  ,     lowercase_		:       List[str]  ,     lowercase_		:       Optional[Any]  ,     lowercase_		:       Optional[Any]  ,     *lowercase_		:       Any				):
     snake_case_ :     int				=	self.num_labels
     snake_case_ :     Any				=	OpenAIGPTForSequenceClassification(lowercase_				)
     model.to(lowercase_				)
     model.eval()

     snake_case_ :     Optional[int]				=	ids_tensor([self.batch_size]  ,     self.type_sequence_label_size				)
     snake_case_ :     Optional[Any]				=	model(lowercase_  ,     token_type_ids=lowercase_  ,     labels=lowercase_				)
     self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.num_labels)				)






 def 						_snake_case					(     self		:       int				):
     snake_case_ :     Dict				=	self.prepare_config_and_inputs()
     (
         (
         snake_case_
     ),	(
         snake_case_
     ),	(
         snake_case_
     ),	(
         snake_case_
     ),	(
         snake_case_
     ),	(
         snake_case_
     ),	(
         snake_case_
     ),	
     ) :     str				=	config_and_inputs
     snake_case_ :     str				=	{
         '''input_ids''': input_ids,
         '''token_type_ids''': token_type_ids,
         '''head_mask''': head_mask,
     }

     return config, inputs_dict





@require_torch
class        _UpperCAmelCase       (			lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     unittest.TestCase):
 _lowerCAmelCase   :			Dict							=		(
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 _lowerCAmelCase   :			int							=		(
     (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
 )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
 _lowerCAmelCase   :			Union[str, Any]							=		(
     {
         """feature-extraction""": OpenAIGPTModel,
         """text-classification""": OpenAIGPTForSequenceClassification,
         """text-generation""": OpenAIGPTLMHeadModel,
         """zero-shot""": OpenAIGPTForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )

 def 						_snake_case					(     self		:       Tuple  ,     lowercase_		:       Optional[int]  ,     lowercase_		:       int  ,     lowercase_		:       List[Any]  ,     lowercase_		:       List[Any]  ,     lowercase_		:       Union[str, Any]				):
     if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
         # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
         # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
         # tiny config could not be created.
         return True

     return False

 def 						_snake_case					(     self		:       Optional[int]  ,     lowercase_		:       List[Any]  ,     lowercase_		:       Optional[int]  ,     lowercase_		:       List[str]=False				):
     snake_case_ :     Dict				=	super()._prepare_for_class(lowercase_  ,     lowercase_  ,     return_labels=lowercase_				)

     if return_labels:
         if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
             snake_case_ :     List[str]				=	torch.zeros(
                 (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)  ,     dtype=torch.long  ,     device=lowercase_  ,     )
             snake_case_ :     int				=	inputs_dict['''labels''']
             snake_case_ :     Optional[Any]				=	inputs_dict['''labels''']
             snake_case_ :     int				=	torch.zeros(
                 (self.model_tester.batch_size, self.model_tester.num_choices)  ,     dtype=torch.long  ,     device=lowercase_  ,     )
             snake_case_ :     Tuple				=	torch.zeros(
                 self.model_tester.batch_size  ,     dtype=torch.long  ,     device=lowercase_				)
     return inputs_dict

 def 						_snake_case					(     self		:       Any				):
     snake_case_ :     List[str]				=	OpenAIGPTModelTester(self				)
     snake_case_ :     Dict				=	ConfigTester(self  ,     config_class=lowercase_  ,     n_embd=37				)

 def 						_snake_case					(     self		:       List[str]				):
     self.config_tester.run_common_tests()

 def 						_snake_case					(     self		:       Optional[Any]				):
     snake_case_ :     Tuple				=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_openai_gpt_model(*lowercase_				)

 def 						_snake_case					(     self		:       List[str]				):
     snake_case_ :     List[str]				=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_lm_head_model(*lowercase_				)

 def 						_snake_case					(     self		:       int				):
     snake_case_ :     Any				=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_double_lm_head_model(*lowercase_				)

 def 						_snake_case					(     self		:       List[str]				):
     snake_case_ :     Optional[int]				=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowercase_				)






 @slow
 def 						_snake_case					(     self		:       Dict				):
     for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_ :     Optional[Any]				=	OpenAIGPTModel.from_pretrained(lowercase_				)
         self.assertIsNotNone(lowercase_				)





@require_torch
class        _UpperCAmelCase       (			unittest.TestCase):

 @slow
 def 						_snake_case					(     self		:       Optional[int]				):
     snake_case_ :     Optional[Any]				=	OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''				)
     model.to(lowercase_				)
     snake_case_ :     List[str]				=	torch.tensor([[481, 4735, 544]]  ,     dtype=torch.long  ,     device=lowercase_				)  # the president is
     snake_case_ :     List[Any]				=	[
         481,
         4735,
         544,
         246,
         963,
         870,
         762,
         239,
         244,
         40477,
         244,
         249,
         719,
         881,
         487,
         544,
         240,
         244,
         603,
         481,
     ]  # the president is a very good man. " \n " i\'m sure he is, " said the

     snake_case_ :     Optional[Any]				=	model.generate(lowercase_  ,     do_sample=lowercase_				)
     self.assertListEqual(output_ids[0].tolist()  ,     lowercase_				)





