



'''simple docstring'''




import json
from typing import List, Optional, Tuple

from tokenizers import normalizers
from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_roformer import RoFormerTokenizer
from .tokenization_utils import JiebaPreTokenizer


a     :    Union[str, Any]      						=					logging.get_logger(__name__)

a     :    Dict      						=					{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

a     :    List[str]      						=					{
    """vocab_file""": {
        """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""",
        """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""",
        """junnyu/roformer_chinese_char_small""": (
            """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt"""
        ),
        """junnyu/roformer_chinese_char_base""": (
            """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt"""
        ),
        """junnyu/roformer_small_discriminator""": (
            """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt"""
        ),
        """junnyu/roformer_small_generator""": (
            """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt"""
        ),
    }
}

a     :    Optional[Any]      						=					{
    """junnyu/roformer_chinese_small""": 1_5_3_6,
    """junnyu/roformer_chinese_base""": 1_5_3_6,
    """junnyu/roformer_chinese_char_small""": 5_1_2,
    """junnyu/roformer_chinese_char_base""": 5_1_2,
    """junnyu/roformer_small_discriminator""": 1_2_8,
    """junnyu/roformer_small_generator""": 1_2_8,
}


a     :    int      						=					{
    """junnyu/roformer_chinese_small""": {"""do_lower_case""": True},
    """junnyu/roformer_chinese_base""": {"""do_lower_case""": True},
    """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True},
    """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True},
    """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True},
    """junnyu/roformer_small_generator""": {"""do_lower_case""": True},
}

class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				VOCAB_FILES_NAMES
	lowercase    =				PRETRAINED_VOCAB_FILES_MAP
	lowercase    =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase    =				PRETRAINED_INIT_CONFIGURATION
	lowercase    =				RoFormerTokenizer





	def __init__(						self	,	A=None	,	A=None	,	A=True	,	A="[UNK]"	,	A="[SEP]"	,	A="[PAD]"	,	A="[CLS]"	,	A="[MASK]"	,	A=True	,	A=None	,	**A	,	)    ->    Tuple:
								super().__init__(
								    A	,	tokenizer_file=A	,	do_lower_case=A	,	unk_token=A	,	sep_token=A	,	pad_token=A	,	cls_token=A	,	mask_token=A	,	tokenize_chinese_chars=A	,	strip_accents=A	,	**A	,	)

								UpperCAmelCase  :	Any							  =	json.loads(self.backend_tokenizer.normalizer.__getstate__()					)
								if (
								    pre_tok_state.get("""lowercase"""	,	A					) != do_lower_case
								    or pre_tok_state.get("""strip_accents"""	,	A					) != strip_accents
								):
															UpperCAmelCase  :	Any							  =	getattr(A	,	pre_tok_state.pop("""type"""					)					)
															UpperCAmelCase  :	str							  =	do_lower_case
															UpperCAmelCase  :	Optional[Any]							  =	strip_accents
															UpperCAmelCase  :	Optional[int]							  =	pre_tok_class(**A					)

								UpperCAmelCase  :	str							  =	do_lower_case





	def __getstate__(						self					)    ->    Any:
								UpperCAmelCase  :	List[Any]							  =	self.__dict__.copy()
								UpperCAmelCase  :	Tuple							  =	BertPreTokenizer()
								return state





	def __setstate__(						self	,	A					)    ->    List[Any]:
								UpperCAmelCase  :	int							  =	d
								UpperCAmelCase  :	List[str]							  =	self.__dict__["""_tokenizer"""].get_vocab()
								UpperCAmelCase  :	Optional[int]							  =	PreTokenizer.custom(JiebaPreTokenizer(A					)					)





	def 				_lowercase(						self	,	A	,	A=None					)    ->    Tuple:
								UpperCAmelCase  :	List[Any]							  =	[self.cls_token_id] + token_ids_a + [self.sep_token_id]

								if token_ids_a:
															output += token_ids_a + [self.sep_token_id]

								return output





	def 				_lowercase(						self	,	A	,	A = None					)    ->    List[int]:
								UpperCAmelCase  :	Optional[Any]							  =	[self.sep_token_id]
								UpperCAmelCase  :	Dict							  =	[self.cls_token_id]
								if token_ids_a is None:
															return len(cls + token_ids_a + sep					) * [0]
								return len(cls + token_ids_a + sep					) * [0] + len(token_ids_a + sep					) * [1]





	def 				_lowercase(						self	,	A	,	A = None					)    ->    Tuple[str]:
								UpperCAmelCase  :	Dict							  =	self._tokenizer.model.save(A	,	name=A					)
								return tuple(A					)






	def 				_lowercase(						self	,	A	,	A=None	,	A=None	,	A=False	,	**A	,	)    ->    List[Any]:
								UpperCAmelCase  :	Optional[int]							  =	BertPreTokenizer()
								return super().save_pretrained(A	,	A	,	A	,	A	,	**A					)






'''simple docstring'''




# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
							import jax
							import jaxlib

a     :    Any      						=					get_logger()

a     :    Optional[dict]      						=					None

class     UpperCamelCase_				(							TensorFormatter[Mapping, 'jax.Array', Mapping]    ):





	def __init__(						self	,	A=None	,	A=None	,	**A					)    ->    str:
								super().__init__(features=A					)
								import jax
								from jaxlib.xla_client import Device

								if isinstance(A	,	A					):
															raise ValueError(
															    f'''Expected {device} to be a `str` not {type(A					)}, as `jaxlib.xla_extension.Device` '''
															    """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """
															    """the device with `str()` to get its string identifier that will be internally mapped """
															    """to the actual `jaxlib.xla_extension.Device`."""					)
								UpperCAmelCase  :	Optional[int]							  =	device if isinstance(A	,	A					) else str(jax.devices()[0]					)
								# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
								# with `pickle` nor with `dill`, so we need to use a global variable instead
								global DEVICE_MAPPING
								if DEVICE_MAPPING is None:
															UpperCAmelCase  :	Any							  =	self._map_devices_to_str()
								if self.device not in list(DEVICE_MAPPING.keys()					):
															logger.warning(
															    f'''Device with string identifier {self.device} not listed among the available '''
															    f'''devices: {list(DEVICE_MAPPING.keys()					)}, so falling back to the default '''
															    f'''device: {str(jax.devices()[0]					)}.'''					)
															UpperCAmelCase  :	List[Any]							  =	str(jax.devices()[0]					)
								UpperCAmelCase  :	Union[str, Any]							  =	jnp_array_kwargs





	@staticmethod
	def 				_lowercase(						)    ->    Dict[str, "jaxlib.xla_extension.Device"]:
								import jax

								return {str(A					): device for device in jax.devices()}





	def 				_lowercase(						self	,	A					)    ->    str:
								import jax
								import jax.numpy as jnp

								if isinstance(A	,	A					) and column:
															if all(
															    isinstance(A	,	jax.Array					) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column					):
																						return jnp.stack(A	,	axis=0					)
								return column





	def 				_lowercase(						self	,	A					)    ->    Tuple:
								import jax
								import jax.numpy as jnp

								if isinstance(A	,	(str, bytes, type(A					))					):
															return value
								elif isinstance(A	,	(np.character, np.ndarray)					) and np.issubdtype(value.dtype	,	np.character					):
															return value.tolist()

								UpperCAmelCase  :	List[str]							  =	{}

								if isinstance(A	,	(np.number, np.ndarray)					) and np.issubdtype(value.dtype	,	np.integer					):
															# the default int precision depends on the jax config
															# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
															if jax.config.jax_enable_xaa:
																						UpperCAmelCase  :	str							  =	{"""dtype""": jnp.intaa}
															else:
																						UpperCAmelCase  :	int							  =	{"""dtype""": jnp.intaa}
								elif isinstance(A	,	(np.number, np.ndarray)					) and np.issubdtype(value.dtype	,	np.floating					):
															UpperCAmelCase  :	Any							  =	{"""dtype""": jnp.floataa}
								elif config.PIL_AVAILABLE and "PIL" in sys.modules:
															import PIL.Image

															if isinstance(A	,	PIL.Image.Image					):
																						UpperCAmelCase  :	List[str]							  =	np.asarray(A					)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
								global DEVICE_MAPPING
								if DEVICE_MAPPING is None:
															UpperCAmelCase  :	Dict							  =	self._map_devices_to_str()

								with jax.default_device(DEVICE_MAPPING[self.device]					):
															# calling jnp.array on a np.ndarray does copy the data
															# see https://github.com/google/jax/issues/4486
															return jnp.array(A	,	**{**default_dtype, **self.jnp_array_kwargs}					)





	def 				_lowercase(						self	,	A					)    ->    Tuple:
								import jax

								# support for torch, tf, jax etc.
								if config.TORCH_AVAILABLE and "torch" in sys.modules:
															import torch

															if isinstance(A	,	torch.Tensor					):
																						return self._tensorize(data_struct.detach().cpu().numpy()[()]					)
								if hasattr(A	,	"""__array__"""					) and not isinstance(A	,	jax.Array					):
															UpperCAmelCase  :	Optional[int]							  =	data_struct.__array__()
								# support for nested types like struct of list of struct
								if isinstance(A	,	np.ndarray					):
															if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
																						return self._consolidate([self.recursive_tensorize(A					) for substruct in data_struct]					)
								elif isinstance(A	,	(list, tuple)					):
															return self._consolidate([self.recursive_tensorize(A					) for substruct in data_struct]					)
								return self._tensorize(A					)





	def 				_lowercase(						self	,	A					)    ->    Dict:
								return map_nested(self._recursive_tensorize	,	A	,	map_list=A					)





	def 				_lowercase(						self	,	A					)    ->    Mapping:
								UpperCAmelCase  :	Union[str, Any]							  =	self.numpy_arrow_extractor().extract_row(A					)
								UpperCAmelCase  :	Dict							  =	self.python_features_decoder.decode_row(A					)
								return self.recursive_tensorize(A					)





	def 				_lowercase(						self	,	A					)    ->    "jax.Array":
								UpperCAmelCase  :	int							  =	self.numpy_arrow_extractor().extract_column(A					)
								UpperCAmelCase  :	Optional[Any]							  =	self.python_features_decoder.decode_column(A	,	pa_table.column_names[0]					)
								UpperCAmelCase  :	Optional[int]							  =	self.recursive_tensorize(A					)
								UpperCAmelCase  :	Any							  =	self._consolidate(A					)
								return column






	def 				_lowercase(						self	,	A					)    ->    Mapping:
								UpperCAmelCase  :	Optional[int]							  =	self.numpy_arrow_extractor().extract_batch(A					)
								UpperCAmelCase  :	List[str]							  =	self.python_features_decoder.decode_batch(A					)
								UpperCAmelCase  :	Union[str, Any]							  =	self.recursive_tensorize(A					)
								for column_name in batch:
															UpperCAmelCase  :	Optional[Any]							  =	self._consolidate(batch[column_name]					)
								return batch

