



from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A__								=						logging.get_logger(__name__)


class       a							(			__lowerCamelCase				):
		__lowerCAmelCase	:    Optional[int]											=					["""pixel_values"""]



		def __init__(     self     :int   ,__lowercase     :bool = True   ,__lowercase     :Dict[str, int] = None   ,__lowercase     :PILImageResampling = PILImageResampling.BICUBIC   ,__lowercase     :bool = True   ,__lowercase     :Dict[str, int] = None   ,__lowercase     :bool = True   ,__lowercase     :Union[int, float] = 1 / 2_5_5   ,__lowercase     :bool = True   ,__lowercase     :Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN   ,__lowercase     :Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD   ,**__lowercase     :List[Any]   ,):
						super().__init__(**__lowercase  )
						snake_case__	:      List[str]     		=	size if size is not None else {'''shortest_edge''': 2_2_4}
						snake_case__	:      int     		=	get_size_dict(__lowercase   ,default_to_square=__lowercase  )
						snake_case__	:      List[Any]     		=	crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
						snake_case__	:      Any     		=	get_size_dict(__lowercase   ,param_name='''crop_size'''  )

						snake_case__	:      Union[str, Any]     		=	do_resize
						snake_case__	:      Dict     		=	size
						snake_case__	:      Optional[int]     		=	resample
						snake_case__	:      Dict     		=	do_center_crop
						snake_case__	:      str     		=	crop_size
						snake_case__	:      str     		=	do_rescale
						snake_case__	:      int     		=	rescale_factor
						snake_case__	:      str     		=	do_normalize
						snake_case__	:      Any     		=	image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
						snake_case__	:      Dict     		=	image_std if image_std is not None else IMAGENET_DEFAULT_STD



		def 	__lowerCamelCase			(     self     :Dict   ,__lowercase     :np.ndarray   ,__lowercase     :Dict[str, int]   ,__lowercase     :PILImageResampling = PILImageResampling.BICUBIC   ,__lowercase     :Optional[Union[str, ChannelDimension]] = None   ,**__lowercase     :List[Any]   ,):
						snake_case__	:      str     		=	get_size_dict(__lowercase   ,default_to_square=__lowercase  )
						# size_dict is a dict with either keys "height" and "width" or "shortest_edge"
						if "shortest_edge" in size:
										snake_case__	:      Any     		=	int((2_5_6 / 2_2_4) * size['''shortest_edge''']  )
										snake_case__	:      int     		=	get_resize_output_image_size(__lowercase   ,size=__lowercase   ,default_to_square=__lowercase  )
										snake_case__	:      List[str]     		=	{'''height''': output_size[0], '''width''': output_size[1]}
						if "height" not in size_dict or "width" not in size_dict:
										raise ValueError(
										    F"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"""  )
						return resize(
						    __lowercase   ,size=(size_dict['''height'''], size_dict['''width'''])   ,resample=__lowercase   ,data_format=__lowercase   ,**__lowercase  )



		def 	__lowerCamelCase			(     self     :Union[str, Any]   ,__lowercase     :np.ndarray   ,__lowercase     :Dict[str, int]   ,__lowercase     :Optional[Union[str, ChannelDimension]] = None   ,**__lowercase     :Optional[int]   ,):
						snake_case__	:      Any     		=	get_size_dict(__lowercase  )
						if "height" not in size or "width" not in size:
										raise ValueError(F"""Size dict must have keys 'height' and 'width'. Got {size.keys()}"""  )
						return center_crop(__lowercase   ,size=(size['''height'''], size['''width'''])   ,data_format=__lowercase   ,**__lowercase  )



		def 	__lowerCamelCase			(     self     :Optional[int]   ,__lowercase     :np.ndarray   ,__lowercase     :Union[int, float]   ,__lowercase     :Optional[Union[str, ChannelDimension]] = None   ,**__lowercase     :List[Any]   ,):
						return rescale(__lowercase   ,scale=__lowercase   ,data_format=__lowercase   ,**__lowercase  )



		def 	__lowerCamelCase			(     self     :str   ,__lowercase     :np.ndarray   ,__lowercase     :Union[float, List[float]]   ,__lowercase     :Union[float, List[float]]   ,__lowercase     :Optional[Union[str, ChannelDimension]] = None   ,**__lowercase     :Optional[Any]   ,):
						return normalize(__lowercase   ,mean=__lowercase   ,std=__lowercase   ,data_format=__lowercase   ,**__lowercase  )






		def 	__lowerCamelCase			(     self     :int   ,__lowercase     :ImageInput   ,__lowercase     :Optional[bool] = None   ,__lowercase     :Optional[Dict[str, int]] = None   ,__lowercase     :PILImageResampling = None   ,__lowercase     :Optional[bool] = None   ,__lowercase     :Optional[Dict[str, int]] = None   ,__lowercase     :Optional[bool] = None   ,__lowercase     :Optional[float] = None   ,__lowercase     :Optional[bool] = None   ,__lowercase     :Optional[Union[float, Iterable[float]]] = None   ,__lowercase     :Optional[Union[float, Iterable[float]]] = None   ,__lowercase     :Optional[TensorType] = None   ,__lowercase     :ChannelDimension = ChannelDimension.FIRST   ,**__lowercase     :int   ,):
						snake_case__	:      str     		=	do_resize if do_resize is not None else self.do_resize
						snake_case__	:      List[Any]     		=	resample if resample is not None else self.resample
						snake_case__	:      int     		=	do_center_crop if do_center_crop is not None else self.do_center_crop
						snake_case__	:      List[str]     		=	do_rescale if do_rescale is not None else self.do_rescale
						snake_case__	:      List[str]     		=	rescale_factor if rescale_factor is not None else self.rescale_factor
						snake_case__	:      List[str]     		=	do_normalize if do_normalize is not None else self.do_normalize
						snake_case__	:      Optional[Any]     		=	image_mean if image_mean is not None else self.image_mean
						snake_case__	:      Optional[int]     		=	image_std if image_std is not None else self.image_std

						snake_case__	:      Tuple     		=	size if size is not None else self.size
						snake_case__	:      List[Any]     		=	get_size_dict(__lowercase   ,default_to_square=__lowercase  )
						snake_case__	:      Union[str, Any]     		=	crop_size if crop_size is not None else self.crop_size
						snake_case__	:      Optional[int]     		=	get_size_dict(__lowercase   ,param_name='''crop_size'''  )

						snake_case__	:      str     		=	make_list_of_images(__lowercase  )

						if not valid_images(__lowercase  ):
										raise ValueError(
										    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
										    '''torch.Tensor, tf.Tensor or jax.ndarray.'''  )

						if do_resize and size is None:
										raise ValueError('''Size must be specified if do_resize is True.'''  )

						if do_center_crop and crop_size is None:
										raise ValueError('''Crop size must be specified if do_center_crop is True.'''  )

						if do_rescale and rescale_factor is None:
										raise ValueError('''Rescale factor must be specified if do_rescale is True.'''  )

						if do_normalize and (image_mean is None or image_std is None):
										raise ValueError('''Image mean and std must be specified if do_normalize is True.'''  )

						# All transformations expect numpy arrays.
						snake_case__	:      Tuple     		=	[to_numpy_array(__lowercase  ) for image in images]

						if do_resize:
										snake_case__	:      Dict     		=	[self.resize(__lowercase   ,__lowercase   ,__lowercase  ) for image in images]

						if do_center_crop:
										snake_case__	:      Any     		=	[self.center_crop(__lowercase   ,__lowercase  ) for image in images]

						if do_rescale:
										snake_case__	:      Tuple     		=	[self.rescale(__lowercase   ,__lowercase  ) for image in images]

						if do_normalize:
										snake_case__	:      Optional[Any]     		=	[self.normalize(__lowercase   ,__lowercase   ,__lowercase  ) for image in images]

						snake_case__	:      int     		=	[to_channel_dimension_format(__lowercase   ,__lowercase  ) for image in images]

						snake_case__	:      Union[str, Any]     		=	{'''pixel_values''': images}
						return BatchFeature(data=__lowercase   ,tensor_type=__lowercase  )






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


A__								=						logging.get_logger(__name__)

A__								=						{'''vocab_file''': '''spiece.model'''}

A__								=						{
    '''vocab_file''': {
        '''TsinghuaAI/CPM-Generate''': '''https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model''',
    }
}


class       a							(			__lowerCamelCase				):



		def __init__(     self     :Union[str, Any]   ,__lowercase     :Optional[Any]   ,__lowercase     :int=False   ,__lowercase     :int=True   ,__lowercase     :Optional[int]=False   ,__lowercase     :List[str]="<s>"   ,__lowercase     :str="</s>"   ,__lowercase     :Dict="<unk>"   ,__lowercase     :Optional[int]="<sep>"   ,__lowercase     :Tuple="<pad>"   ,__lowercase     :Union[str, Any]="<cls>"   ,__lowercase     :Dict="<mask>"   ,__lowercase     :List[Any]=["<eop>", "<eod>"]   ,__lowercase     :Optional[Dict[str, Any]] = None   ,**__lowercase     :int   ,):
						snake_case__	:      Any     		=	AddedToken(__lowercase   ,lstrip=__lowercase   ,rstrip=__lowercase  ) if isinstance(__lowercase   ,__lowercase  ) else mask_token

						snake_case__	:      Tuple     		=	{} if sp_model_kwargs is None else sp_model_kwargs

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

						snake_case__	:      Optional[Any]     		=	3

						snake_case__	:      List[str]     		=	do_lower_case
						snake_case__	:      Union[str, Any]     		=	remove_space
						snake_case__	:      Tuple     		=	keep_accents
						snake_case__	:      List[str]     		=	vocab_file

						snake_case__	:      Optional[Any]     		=	spm.SentencePieceProcessor(**self.sp_model_kwargs  )
						self.sp_model.Load(__lowercase  )

						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.'''  )
						snake_case__	:      List[Any]     		=	jieba
						snake_case__	:      Union[str, Any]     		=	str.maketrans(''' \n'''   ,'''\u2582\u2583'''  )



		@property
		# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
		def 	__lowerCamelCase			(     self     :Union[str, Any]  ):
						return len(self.sp_model  )



		def 	__lowerCamelCase			(     self     :Any  ):
						snake_case__	:      Optional[Any]     		=	{self.convert_ids_to_tokens(__lowercase  ): i for i in range(self.vocab_size  )}
						vocab.update(self.added_tokens_encoder  )
						return vocab



		def __getstate__(     self     :List[str]  ):
						snake_case__	:      Optional[Any]     		=	self.__dict__.copy()
						snake_case__	:      Optional[int]     		=	None
						return state



		def __setstate__(     self     :int   ,__lowercase     :str  ):
						snake_case__	:      Tuple     		=	d

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

						snake_case__	:      List[Any]     		=	spm.SentencePieceProcessor(**self.sp_model_kwargs  )
						self.sp_model.Load(self.vocab_file  )



		def 	__lowerCamelCase			(     self     :Dict   ,__lowercase     :Optional[int]  ):
						if self.remove_space:
										snake_case__	:      int     		=	''' '''.join(inputs.strip().split()  )
						else:
										snake_case__	:      Tuple     		=	inputs
						snake_case__	:      List[Any]     		=	outputs.replace('''``'''   ,'''"'''  ).replace('''\'\''''   ,'''"'''  )

						if not self.keep_accents:
										snake_case__	:      Any     		=	unicodedata.normalize('''NFKD'''   ,__lowercase  )
										snake_case__	:      Dict     		=	''''''.join([c for c in outputs if not unicodedata.combining(__lowercase  )]  )
						if self.do_lower_case:
										snake_case__	:      str     		=	outputs.lower()

						return outputs



		def 	__lowerCamelCase			(     self     :Optional[Any]   ,__lowercase     :str  ):
						snake_case__	:      Dict     		=	self.preprocess_text(__lowercase  )
						snake_case__	:      Any     		=	self.sp_model.encode(__lowercase   ,out_type=__lowercase  )
						snake_case__	:      List[str]     		=	[]
						for piece in pieces:
										if len(__lowercase  ) > 1 and piece[-1] == str(''','''  ) and piece[-2].isdigit():
														snake_case__	:      Union[str, Any]     		=	self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowercase   ,''''''  )  )
														if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																		if len(cur_pieces[0]  ) == 1:
																						snake_case__	:      Optional[Any]     		=	cur_pieces[1:]
																		else:
																						snake_case__	:      Optional[Any]     		=	cur_pieces[0][1:]
														cur_pieces.append(piece[-1]  )
														new_pieces.extend(__lowercase  )
										else:
														new_pieces.append(__lowercase  )

						return new_pieces



		def 	__lowerCamelCase			(     self     :Union[str, Any]   ,__lowercase     :Dict  ):
						return self.sp_model.PieceToId(__lowercase  )



		def 	__lowerCamelCase			(     self     :Tuple   ,__lowercase     :Optional[int]  ):
						return self.sp_model.IdToPiece(__lowercase  )



		def 	__lowerCamelCase			(     self     :Tuple   ,__lowercase     :List[Any]  ):
						snake_case__	:      Union[str, Any]     		=	''''''.join(__lowercase  ).replace(__lowercase   ,''' '''  ).strip()
						return out_string



		def 	__lowerCamelCase			(     self     :List[Any]   ,__lowercase     :List[int]   ,__lowercase     :Optional[List[int]] = None  ):
						snake_case__	:      Optional[Any]     		=	[self.sep_token_id]
						snake_case__	:      str     		=	[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     :str   ,__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  )

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



		def 	__lowerCamelCase			(     self     :List[str]   ,__lowercase     :List[int]   ,__lowercase     :Optional[List[int]] = None  ):
						snake_case__	:      List[Any]     		=	[self.sep_token_id]
						snake_case__	:      Optional[Any]     		=	[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     :Optional[int]   ,__lowercase     :str   ,__lowercase     :Optional[str] = None  ):
						if not os.path.isdir(__lowercase  ):
										logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""  )
										return
						snake_case__	:      Union[str, Any]     		=	os.path.join(
						    __lowercase   ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']  )

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

						return (out_vocab_file,)






		def 	__lowerCamelCase			(     self     :Union[str, Any]   ,*__lowercase     :Optional[int]   ,**__lowercase     :Dict  ):
						snake_case__	:      Dict     		=	super()._decode(*__lowercase   ,**__lowercase  )
						snake_case__	:      List[Any]     		=	text.replace(''' '''   ,''''''  ).replace('''\u2582'''   ,''' '''  ).replace('''\u2583'''   ,'''\n'''  )
						return text

