



'''simple docstring'''







import os
import pickle
import tempfile
import unittest
from typing import Callable, Optional

import numpy as np

from transformers import (
    BatchEncoding,
    BertTokenizer,
    BertTokenizerFast,
    PreTrainedTokenizer,
    PreTrainedTokenizerFast,
    TensorType,
    TokenSpan,
    is_tokenizers_available,
)
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow


if is_tokenizers_available():
      from tokenizers import Tokenizer
      from tokenizers.models import WordPiece

class    lowerCamelCase_				(						unittest.TestCase	):






   '''simple docstring'''

   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       UpperCamelCase__	     =      list(tokenizer_class.max_model_input_sizes.keys()			)
       for model_name in sa_models[:1]:
           UpperCamelCase__	     =      tokenizer_class.from_pretrained(lowercase_			)
           self.assertIsNotNone(lowercase_			)
           self.assertIsInstance(lowercase_  ,    lowercase_			)
           self.assertIsInstance(lowercase_  ,    lowercase_			)

           for special_tok in tokenizer.all_special_tokens:
               self.assertIsInstance(lowercase_  ,    lowercase_			)
               UpperCamelCase__	     =      tokenizer.convert_tokens_to_ids(lowercase_			)
               self.assertIsInstance(lowercase_  ,    lowercase_			)


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase = None			):
       UpperCamelCase__	     =      pickle.dumps(lowercase_			)
       self.assertIsNotNone(lowercase_			)

       UpperCamelCase__	     =      pickle.loads(lowercase_			)

       # Ensure is_fast is correctly restored
       self.assertEqual(be_restored.is_fast  ,    be_original.is_fast			)

       # Ensure encodings are potentially correctly restored
       if be_original.is_fast:
           self.assertIsNotNone(be_restored.encodings			)
       else:
           self.assertIsNone(be_restored.encodings			)

       # Ensure the keys are the same
       for original_v, restored_v in zip(be_original.values()  ,    be_restored.values()			):
           if equal_op:
               self.assertTrue(equal_op(lowercase_  ,    lowercase_			)			)
           else:
               self.assertEqual(lowercase_  ,    lowercase_			)


   @slow
   def 						_UpperCamelCase							(	self			):
       self.check_tokenizer_from_pretrained(lowercase_			)


   def 						_UpperCamelCase							(	self			):
       self.assertEqual(TensorType("tf"			)  ,    TensorType.TENSORFLOW			)
       self.assertEqual(TensorType("pt"			)  ,    TensorType.PYTORCH			)
       self.assertEqual(TensorType("np"			)  ,    TensorType.NUMPY			)


   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       import numpy as np

       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)
       UpperCamelCase__	     =      BertTokenizerFast.from_pretrained("bert-base-cased"			)

       # Python no tensor
       with self.subTest("BatchEncoding (Python, return_tensors=None)"			):
           self.assert_dump_and_restore(tokenizer_p("Small example to encode"			)			)

       with self.subTest("BatchEncoding (Python, return_tensors=NUMPY)"			):
           self.assert_dump_and_restore(
               tokenizer_p("Small example to encode"  ,    return_tensors=TensorType.NUMPY			)  ,    np.array_equal			)

       with self.subTest("BatchEncoding (Rust, return_tensors=None)"			):
           self.assert_dump_and_restore(tokenizer_r("Small example to encode"			)			)

       with self.subTest("BatchEncoding (Rust, return_tensors=NUMPY)"			):
           self.assert_dump_and_restore(
               tokenizer_r("Small example to encode"  ,    return_tensors=TensorType.NUMPY			)  ,    np.array_equal			)


   @require_tf
   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       import tensorflow as tf

       def tf_array_equals(__UpperCamelCase  ,    __UpperCamelCase			):
           return tf.reduce_all(tf.equal(lowercase_  ,    lowercase_			)			)

       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)
       UpperCamelCase__	     =      BertTokenizerFast.from_pretrained("bert-base-cased"			)

       with self.subTest("BatchEncoding (Python, return_tensors=TENSORFLOW)"			):
           self.assert_dump_and_restore(
               tokenizer_p("Small example to encode"  ,    return_tensors=TensorType.TENSORFLOW			)  ,    lowercase_			)

       with self.subTest("BatchEncoding (Rust, return_tensors=TENSORFLOW)"			):
           self.assert_dump_and_restore(
               tokenizer_r("Small example to encode"  ,    return_tensors=TensorType.TENSORFLOW			)  ,    lowercase_			)


   @require_torch
   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       import torch

       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)
       UpperCamelCase__	     =      BertTokenizerFast.from_pretrained("bert-base-cased"			)

       with self.subTest("BatchEncoding (Python, return_tensors=PYTORCH)"			):
           self.assert_dump_and_restore(
               tokenizer_p("Small example to encode"  ,    return_tensors=TensorType.PYTORCH			)  ,    torch.equal			)

       with self.subTest("BatchEncoding (Rust, return_tensors=PYTORCH)"			):
           self.assert_dump_and_restore(
               tokenizer_r("Small example to encode"  ,    return_tensors=TensorType.PYTORCH			)  ,    torch.equal			)


   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)
       UpperCamelCase__	     =      BertTokenizerFast.from_pretrained("bert-base-cased"			)

       with self.subTest("Python Tokenizer"			):
           self.assertFalse(tokenizer_p("Small example to_encode"			).is_fast			)

       with self.subTest("Rust Tokenizer"			):
           self.assertTrue(tokenizer_r("Small example to_encode"			).is_fast			)


   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      BertTokenizerFast.from_pretrained("bert-base-cased"			)
       UpperCamelCase__	     =      tokenizer_r(["Test", "\xad", "test"]  ,    is_split_into_words=lowercase_			)

       self.assertEqual(encoded.word_to_tokens(0			)  ,    TokenSpan(start=1  ,    end=2			)			)
       self.assertEqual(encoded.word_to_tokens(1			)  ,    lowercase_			)
       self.assertEqual(encoded.word_to_tokens(2			)  ,    TokenSpan(start=2  ,    end=3			)			)


   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="np"			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (2, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (2,)			)
       # test converting the converted
       with CaptureStderr() as cs:
           UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="np"			)
       self.assertFalse(len(cs.err			)  ,    msg=f'should have no warning, but got {cs.err}'			)

       UpperCamelCase__	     =      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="np"  ,    prepend_batch_axis=lowercase_			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (1, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (1,)			)


   @require_torch
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="pt"			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (2, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (2,)			)
       # test converting the converted
       with CaptureStderr() as cs:
           UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="pt"			)
       self.assertFalse(len(cs.err			)  ,    msg=f'should have no warning, but got {cs.err}'			)

       UpperCamelCase__	     =      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="pt"  ,    prepend_batch_axis=lowercase_			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (1, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (1,)			)


   @require_tf
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="tf"			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (2, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (2,)			)
       # test converting the converted
       with CaptureStderr() as cs:
           UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="tf"			)
       self.assertFalse(len(cs.err			)  ,    msg=f'should have no warning, but got {cs.err}'			)

       UpperCamelCase__	     =      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="tf"  ,    prepend_batch_axis=lowercase_			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (1, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (1,)			)


   @require_flax
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="jax"			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (2, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (2,)			)
       # test converting the converted
       with CaptureStderr() as cs:
           UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="jax"			)
       self.assertFalse(len(cs.err			)  ,    msg=f'should have no warning, but got {cs.err}'			)

       UpperCamelCase__	     =      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}			)
       UpperCamelCase__	     =      batch.convert_to_tensors(tensor_type="jax"  ,    prepend_batch_axis=lowercase_			)
       self.assertEqual(tensor_batch["inputs"].shape  ,    (1, 3)			)
       self.assertEqual(tensor_batch["labels"].shape  ,    (1,)			)


   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      [{"""input_ids""": np.array([0, 1, 2]			)}, {"""input_ids""": np.array([0, 1, 2, 3]			)}]
       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)

       UpperCamelCase__	     =      tokenizer.pad(lowercase_  ,    padding=lowercase_			)
       self.assertTrue(isinstance(batch["input_ids"]  ,    np.ndarray			)			)
       self.assertEqual(batch["input_ids"].tolist()  ,    [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]			)
       UpperCamelCase__	     =      tokenizer.pad(lowercase_  ,    padding=lowercase_  ,    return_tensors="np"			)
       self.assertTrue(isinstance(batch["input_ids"]  ,    np.ndarray			)			)
       self.assertEqual(batch["input_ids"].tolist()  ,    [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]			)


   @require_torch
   def 						_UpperCamelCase							(	self			):
       import torch

       UpperCamelCase__	     =      [{"""input_ids""": torch.tensor([0, 1, 2]			)}, {"""input_ids""": torch.tensor([0, 1, 2, 3]			)}]
       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)

       UpperCamelCase__	     =      tokenizer.pad(lowercase_  ,    padding=lowercase_			)
       self.assertTrue(isinstance(batch["input_ids"]  ,    torch.Tensor			)			)
       self.assertEqual(batch["input_ids"].tolist()  ,    [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]			)
       UpperCamelCase__	     =      tokenizer.pad(lowercase_  ,    padding=lowercase_  ,    return_tensors="pt"			)
       self.assertTrue(isinstance(batch["input_ids"]  ,    torch.Tensor			)			)
       self.assertEqual(batch["input_ids"].tolist()  ,    [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]			)


   @require_tf
   def 						_UpperCamelCase							(	self			):
       import tensorflow as tf

       UpperCamelCase__	     =      [{"""input_ids""": tf.constant([0, 1, 2]			)}, {"""input_ids""": tf.constant([0, 1, 2, 3]			)}]
       UpperCamelCase__	     =      BertTokenizer.from_pretrained("bert-base-cased"			)

       UpperCamelCase__	     =      tokenizer.pad(lowercase_  ,    padding=lowercase_			)
       self.assertTrue(isinstance(batch["input_ids"]  ,    tf.Tensor			)			)
       self.assertEqual(batch["input_ids"].numpy().tolist()  ,    [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]			)
       UpperCamelCase__	     =      tokenizer.pad(lowercase_  ,    padding=lowercase_  ,    return_tensors="tf"			)
       self.assertTrue(isinstance(batch["input_ids"]  ,    tf.Tensor			)			)
       self.assertEqual(batch["input_ids"].numpy().tolist()  ,    [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]			)


   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      Tokenizer(WordPiece(unk_token="[UNK]"			)			)
       PreTrainedTokenizerFast(tokenizer_object=lowercase_			)







   @require_tokenizers
   def 						_UpperCamelCase							(	self			):
       UpperCamelCase__	     =      Tokenizer(WordPiece(unk_token="[UNK]"			)			)
       with tempfile.TemporaryDirectory() as tmpdirname:
           bert_tokenizer.save(os.path.join(lowercase_  ,    "tokenizer.json"			)			)
           PreTrainedTokenizerFast(tokenizer_file=os.path.join(lowercase_  ,    "tokenizer.json"			)			)





'''simple docstring'''




from typing import Dict, List, Optional, Union

import numpy as np

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


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


if is_vision_available():
						import PIL





class        __magic_name__		(       _UpperCAmelCase):
			UpperCamelCase__							=			['''pixel_values''']







			def __init__(      self							:    Any							,     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 / 255							,     lowercase_							:    bool = True							,     lowercase_							:    Optional[Union[float, List[float]]] = None							,     lowercase_							:    Optional[Union[float, List[float]]] = None							,     lowercase_							:    bool = True							,     **lowercase_							:    Optional[Any]							,     ):
										super().__init__(**lowercase_       )
										lowercase_   :     List[Any]									=			size if size is not None else {"""shortest_edge""": 224}
										lowercase_   :     int									=			get_size_dict(lowercase_							,     default_to_square=lowercase_       )
										lowercase_   :     List[Any]									=			crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
										lowercase_   :     int									=			get_size_dict(lowercase_       )

										lowercase_   :     Tuple									=			do_resize
										lowercase_   :     int									=			size
										lowercase_   :     List[Any]									=			resample
										lowercase_   :     str									=			do_center_crop
										lowercase_   :     Optional[int]									=			crop_size
										lowercase_   :     str									=			do_rescale
										lowercase_   :     List[Any]									=			rescale_factor
										lowercase_   :     Dict									=			do_normalize
										lowercase_   :     List[str]									=			image_mean if image_mean is not None else OPENAI_CLIP_MEAN
										lowercase_   :     Any									=			image_std if image_std is not None else OPENAI_CLIP_STD
										lowercase_   :     List[str]									=			do_convert_rgb







			def       SCREAMING_SNAKE_CASE_	(      self							:    Union[str, Any]							,     lowercase_							:    np.ndarray							,     lowercase_							:    Dict[str, int]							,     lowercase_							:    PILImageResampling = PILImageResampling.BICUBIC							,     lowercase_							:    Optional[Union[str, ChannelDimension]] = None							,     **lowercase_							:    Dict							,     ):
										lowercase_   :     Tuple									=			get_size_dict(lowercase_							,     default_to_square=lowercase_       )
										lowercase_   :     List[Any]									=			get_resize_output_image_size(
										    lowercase_							,     size=(size["""height"""], size["""width"""])							,     default_to_square=lowercase_       )
										return resize(lowercase_							,     size=lowercase_							,     resample=lowercase_							,     data_format=lowercase_							,     **lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    List[Any]							,     lowercase_							:    np.ndarray							,     lowercase_							:    Dict[str, int]							,     lowercase_							:    Optional[Union[str, ChannelDimension]] = None							,     **lowercase_							:    Any							,     ):
										lowercase_   :     int									=			get_size_dict(lowercase_       )
										return center_crop(lowercase_							,     size=(size["""height"""], size["""width"""])							,     data_format=lowercase_							,     **lowercase_       )







			def       SCREAMING_SNAKE_CASE_	(      self							:    Tuple							,     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       SCREAMING_SNAKE_CASE_	(      self							:    int							,     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       SCREAMING_SNAKE_CASE_	(      self							:    List[Any]							,     lowercase_							:    ImageInput							,     lowercase_							:    bool = None							,     lowercase_							:    Dict[str, int] = None							,     lowercase_							:    PILImageResampling = None							,     lowercase_							:    bool = None							,     lowercase_							:    int = None							,     lowercase_							:    bool = None							,     lowercase_							:    float = None							,     lowercase_							:    bool = None							,     lowercase_							:    Optional[Union[float, List[float]]] = None							,     lowercase_							:    Optional[Union[float, List[float]]] = None							,     lowercase_							:    bool = None							,     lowercase_							:    Optional[Union[str, TensorType]] = None							,     lowercase_							:    Optional[ChannelDimension] = ChannelDimension.FIRST							,     **lowercase_							:    Optional[int]							,     ):
										lowercase_   :     Optional[Any]									=			do_resize if do_resize is not None else self.do_resize
										lowercase_   :     Union[str, Any]									=			size if size is not None else self.size
										lowercase_   :     Optional[int]									=			get_size_dict(lowercase_							,     default_to_square=lowercase_       )
										lowercase_   :     int									=			resample if resample is not None else self.resample
										lowercase_   :     str									=			do_center_crop if do_center_crop is not None else self.do_center_crop
										lowercase_   :     int									=			crop_size if crop_size is not None else self.crop_size
										lowercase_   :     int									=			get_size_dict(lowercase_       )
										lowercase_   :     Dict									=			do_rescale if do_rescale is not None else self.do_rescale
										lowercase_   :     List[str]									=			rescale_factor if rescale_factor is not None else self.rescale_factor
										lowercase_   :     Optional[Any]									=			do_normalize if do_normalize is not None else self.do_normalize
										lowercase_   :     List[Any]									=			image_mean if image_mean is not None else self.image_mean
										lowercase_   :     str									=			image_std if image_std is not None else self.image_std
										lowercase_   :     Any									=			do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

										lowercase_   :     int									=			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."""       )

										# PIL RGBA images are converted to RGB
										if do_convert_rgb:
																	lowercase_   :     Dict									=			[convert_to_rgb(lowercase_       ) for image in images]

										# All transformations expect numpy arrays.
										lowercase_   :     Any									=			[to_numpy_array(lowercase_       ) for image in images]

										if do_resize:
																	lowercase_   :     Union[str, Any]									=			[self.resize(image=lowercase_							,     size=lowercase_							,     resample=lowercase_       ) for image in images]

										if do_center_crop:
																	lowercase_   :     List[str]									=			[self.center_crop(image=lowercase_							,     size=lowercase_       ) for image in images]

										if do_rescale:
																	lowercase_   :     int									=			[self.rescale(image=lowercase_							,     scale=lowercase_       ) for image in images]

										if do_normalize:
																	lowercase_   :     List[Any]									=			[self.normalize(image=lowercase_							,     mean=lowercase_							,     std=lowercase_       ) for image in images]

										lowercase_   :     List[Any]									=			[to_channel_dimension_format(lowercase_							,     lowercase_       ) for image in images]

										lowercase_   :     Any									=			{"""pixel_values""": images}
										return BatchFeature(data=lowercase_							,     tensor_type=lowercase_       )





