




"""simple docstring"""




import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


lowerCAmelCase							:			Any     							=							logging.get_logger(__name__)

lowerCAmelCase							:			List[str]     							=							{"""vocab_file""": """spiece.model"""}

lowerCAmelCase							:			Optional[int]     							=							{
    """vocab_file""": {
        """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""",
    }
}






class     __magic_name__							(       UpperCAmelCase__				):






				'''simple docstring'''





				def __init__(       self		, _a		, _a=False		, _a=True		, _a=False		, _a="<s>"		, _a="</s>"		, _a="<unk>"		, _a="<sep>"		, _a="<pad>"		, _a="<cls>"		, _a="<mask>"		, _a=["<eop>", "<eod>"]		, _a = None		, **_a		, ):





							"""simple docstring"""
							lowerCamelCase			      =					AddedToken(_a		, lstrip=_a		, rstrip=_a ) if isinstance(_a		, _a ) else mask_token

							lowerCamelCase			      =					{} if sp_model_kwargs is None else sp_model_kwargs

							super().__init__(
							    do_lower_case=_a		, remove_space=_a		, keep_accents=_a		, bos_token=_a		, eos_token=_a		, unk_token=_a		, sep_token=_a		, pad_token=_a		, cls_token=_a		, mask_token=_a		, additional_special_tokens=_a		, sp_model_kwargs=self.sp_model_kwargs		, **_a		, )

							lowerCamelCase			      =					3

							lowerCamelCase			      =					do_lower_case
							lowerCamelCase			      =					remove_space
							lowerCamelCase			      =					keep_accents
							lowerCamelCase			      =					vocab_file

							lowerCamelCase			      =					spm.SentencePieceProcessor(**self.sp_model_kwargs )
							self.sp_model.Load(_a )

							try:
										import jieba
							except ModuleNotFoundError as error:
										raise error.__class__(
										    """You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """
										    """See https://pypi.org/project/jieba/ for installation.""" )
							lowerCamelCase			      =					jieba
							lowerCamelCase			      =					str.maketrans(""" \n"""		, """\u2582\u2583""" )





				@property
				# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							return len(self.sp_model )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					{self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )}
							vocab.update(self.added_tokens_encoder )
							return vocab





				def __getstate__(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.__dict__.copy()
							lowerCamelCase			      =					None
							return state





				def __setstate__(       self		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					d

							# for backward compatibility
							if not hasattr(self		, """sp_model_kwargs""" ):
										lowerCamelCase			      =					{}

							lowerCamelCase			      =					spm.SentencePieceProcessor(**self.sp_model_kwargs )
							self.sp_model.Load(self.vocab_file )





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							if self.remove_space:
										lowerCamelCase			      =					""" """.join(inputs.strip().split() )
							else:
										lowerCamelCase			      =					inputs
							lowerCamelCase			      =					outputs.replace("""``"""		, """\"""" ).replace("""''"""		, """\"""" )

							if not self.keep_accents:
										lowerCamelCase			      =					unicodedata.normalize("""NFKD"""		, _a )
										lowerCamelCase			      =					"""""".join([c for c in outputs if not unicodedata.combining(_a )] )
							if self.do_lower_case:
										lowerCamelCase			      =					outputs.lower()

							return outputs





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					self.preprocess_text(_a )
							lowerCamelCase			      =					self.sp_model.encode(_a		, out_type=_a )
							lowerCamelCase			      =					[]
							for piece in pieces:
										if len(_a ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit():
													lowerCamelCase			      =					self.sp_model.EncodeAsPieces(piece[:-1].replace(_a		, """""" ) )
													if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																if len(cur_pieces[0] ) == 1:
																			lowerCamelCase			      =					cur_pieces[1:]
																else:
																			lowerCamelCase			      =					cur_pieces[0][1:]
													cur_pieces.append(piece[-1] )
													new_pieces.extend(_a )
										else:
													new_pieces.append(_a )

							return new_pieces





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							return self.sp_model.PieceToId(_a )





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							return self.sp_model.IdToPiece(_a )





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					"""""".join(_a ).replace(_a		, """ """ ).strip()
							return out_string





				def    _lowerCAmelCase				(       self		, _a		, _a = None ):





							"""simple docstring"""
							lowerCamelCase			      =					[self.sep_token_id]
							lowerCamelCase			      =					[self.cls_token_id]
							if token_ids_a is None:
										return token_ids_a + sep + cls
							return token_ids_a + sep + token_ids_a + sep + cls





				def    _lowerCAmelCase				(       self		, _a		, _a = None		, _a = False ):





							"""simple docstring"""

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

							if token_ids_a is not None:
										return ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1, 1]
							return ([0] * len(_a )) + [1, 1]





				def    _lowerCAmelCase				(       self		, _a		, _a = None ):





							"""simple docstring"""
							lowerCamelCase			      =					[self.sep_token_id]
							lowerCamelCase			      =					[2]

							if token_ids_a is None:
										return len(token_ids_a + sep ) * [0] + cls_segment_id
							return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id





				def    _lowerCAmelCase				(       self		, _a		, _a = None ):





							"""simple docstring"""
							if not os.path.isdir(_a ):
										logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
										return
							lowerCamelCase			      =					os.path.join(
							    _a		, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )

							if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ):
										copyfile(self.vocab_file		, _a )
							elif not os.path.isfile(self.vocab_file ):
										with open(_a		, """wb""" ) as fi:
													lowerCamelCase			      =					self.sp_model.serialized_model_proto()
													fi.write(_a )

							return (out_vocab_file,)





				def    _lowerCAmelCase				(       self		, *_a		, **_a ):





							"""simple docstring"""
							lowerCamelCase			      =					super()._decode(*_a		, **_a )
							lowerCamelCase			      =					text.replace(""" """		, """""" ).replace("""\u2582"""		, """ """ ).replace("""\u2583"""		, """\n""" )
							return text









"""simple docstring"""




import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase							:			int     							=							logging.get_logger(__name__)

lowerCAmelCase							:			List[str]     							=							{
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}






class     __magic_name__							(       UpperCAmelCase__				):






				'''simple docstring'''
				__UpperCamelCase			  =						"sew-d"





				def __init__(       self		, _a=32		, _a=768		, _a=12		, _a=12		, _a=3_072		, _a=2		, _a=512		, _a=256		, _a=True		, _a=True		, _a=("p2c", "c2p")		, _a="layer_norm"		, _a="gelu_python"		, _a=0.1		, _a=0.1		, _a=0.1		, _a=0.0		, _a=0.1		, _a=0.02		, _a=1e-7		, _a=1e-5		, _a="group"		, _a="gelu"		, _a=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)		, _a=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)		, _a=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)		, _a=False		, _a=128		, _a=16		, _a=True		, _a=0.05		, _a=10		, _a=2		, _a=0.0		, _a=10		, _a=0		, _a="mean"		, _a=False		, _a=False		, _a=256		, _a=0		, _a=1		, _a=2		, **_a		, ):





							"""simple docstring"""
							super().__init__(**_a		, pad_token_id=_a		, bos_token_id=_a		, eos_token_id=_a )
							lowerCamelCase			      =					hidden_size
							lowerCamelCase			      =					feat_extract_norm
							lowerCamelCase			      =					feat_extract_activation
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					conv_bias
							lowerCamelCase			      =					num_conv_pos_embeddings
							lowerCamelCase			      =					num_conv_pos_embedding_groups
							lowerCamelCase			      =					len(self.conv_dim )
							lowerCamelCase			      =					num_hidden_layers
							lowerCamelCase			      =					intermediate_size
							lowerCamelCase			      =					squeeze_factor
							lowerCamelCase			      =					max_position_embeddings
							lowerCamelCase			      =					position_buckets
							lowerCamelCase			      =					share_att_key
							lowerCamelCase			      =					relative_attention
							lowerCamelCase			      =					norm_rel_ebd
							lowerCamelCase			      =					list(_a )
							lowerCamelCase			      =					hidden_act
							lowerCamelCase			      =					num_attention_heads
							lowerCamelCase			      =					hidden_dropout
							lowerCamelCase			      =					attention_dropout
							lowerCamelCase			      =					activation_dropout
							lowerCamelCase			      =					feat_proj_dropout
							lowerCamelCase			      =					final_dropout
							lowerCamelCase			      =					layer_norm_eps
							lowerCamelCase			      =					feature_layer_norm_eps
							lowerCamelCase			      =					initializer_range
							lowerCamelCase			      =					vocab_size

							if (
							    (len(self.conv_stride ) != self.num_feat_extract_layers)
							    or (len(self.conv_kernel ) != self.num_feat_extract_layers)
							    or (len(self.conv_dim ) != self.num_feat_extract_layers)
							):
										raise ValueError(
										    """Configuration for convolutional layers is incorrect."""
										    """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
										    f'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'
										    f'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' )

							# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
							lowerCamelCase			      =					apply_spec_augment
							lowerCamelCase			      =					mask_time_prob
							lowerCamelCase			      =					mask_time_length
							lowerCamelCase			      =					mask_time_min_masks
							lowerCamelCase			      =					mask_feature_prob
							lowerCamelCase			      =					mask_feature_length
							lowerCamelCase			      =					mask_feature_min_masks

							# ctc loss
							lowerCamelCase			      =					ctc_loss_reduction
							lowerCamelCase			      =					ctc_zero_infinity

							# sequence classification
							lowerCamelCase			      =					use_weighted_layer_sum
							lowerCamelCase			      =					classifier_proj_size





				@property
				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							return functools.reduce(operator.mul		, self.conv_stride		, 1 )



