





'''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,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__lowerCAmelCase							:     List[str]		     =logging.get_logger(__name__)






class        UpperCAmelCase     (	SCREAMING_SNAKE_CASE__    ):
 __lowercase       		=    ['pixel_values']
 def __init__(    self				:int						,	lowercase_				:bool = True						,	lowercase_				:Optional[Dict[str, int]] = None						,	lowercase_				:PILImageResampling = PILImageResampling.BILINEAR						,	lowercase_				:bool = True						,	lowercase_				:Dict[str, int] = None						,	lowercase_				:bool = True						,	lowercase_				:Union[int, float] = 1 / 2_55						,	lowercase_				:bool = True						,	lowercase_				:Optional[Union[float, List[float]]] = None						,	lowercase_				:Optional[Union[float, List[float]]] = None						,	**lowercase_				:Dict						,	)->							Union[str, Any]:
    super().__init__(**a_							)
    A__    =      size if size is not None else {"shortest_edge": 2_56}
    A__    =      get_size_dict(a_						,	default_to_square=a_							)
    A__    =      crop_size if crop_size is not None else {"height": 2_24, "width": 2_24}
    A__    =      get_size_dict(a_							)
    A__    =      do_resize
    A__    =      size
    A__    =      resample
    A__    =      do_center_crop
    A__    =      crop_size
    A__    =      do_rescale
    A__    =      rescale_factor
    A__    =      do_normalize
    A__    =      image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
    A__    =      image_std if image_std is not None else IMAGENET_STANDARD_STD
 def 					UpperCAmelCase_							(    self				:str						,	lowercase_				:np.ndarray						,	lowercase_				:Dict[str, int]						,	lowercase_				:PILImageResampling = PILImageResampling.BICUBIC						,	lowercase_				:Optional[Union[str, ChannelDimension]] = None						,	**lowercase_				:int						,	)->							Optional[int]:
    A__    =      get_size_dict(a_						,	default_to_square=a_							)
    if "shortest_edge" not in size:
       raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"							)
    A__    =      get_resize_output_image_size(a_						,	size=size["shortest_edge"]						,	default_to_square=a_							)
    return resize(a_						,	size=a_						,	resample=a_						,	data_format=a_						,	**a_							)
 def 					UpperCAmelCase_							(    self				:List[Any]						,	lowercase_				:np.ndarray						,	lowercase_				:Dict[str, int]						,	lowercase_				:Optional[Union[str, ChannelDimension]] = None						,	**lowercase_				:List[str]						,	)->							Tuple:
    A__    =      get_size_dict(a_							)
    return center_crop(a_						,	size=(size["height"], size["width"])						,	data_format=a_						,	**a_							)
 def 					UpperCAmelCase_							(    self				:List[Any]						,	lowercase_				:np.ndarray						,	lowercase_				:float						,	lowercase_				:Optional[Union[str, ChannelDimension]] = None						,	**lowercase_				:List[Any]							)->							List[Any]:
    return rescale(a_						,	scale=a_						,	data_format=a_						,	**a_							)
 def 					UpperCAmelCase_							(    self				:Optional[Any]						,	lowercase_				:np.ndarray						,	lowercase_				:Union[float, List[float]]						,	lowercase_				:Union[float, List[float]]						,	lowercase_				:Optional[Union[str, ChannelDimension]] = None						,	**lowercase_				:Any						,	)->							Optional[Any]:
    return normalize(a_						,	mean=a_						,	std=a_						,	data_format=a_						,	**a_							)



 def 					UpperCAmelCase_							(    self				:List[Any]						,	lowercase_				:ImageInput						,	lowercase_				:Optional[bool] = None						,	lowercase_				:Dict[str, int] = None						,	lowercase_				:PILImageResampling = None						,	lowercase_				:bool = None						,	lowercase_				:Dict[str, int] = None						,	lowercase_				:Optional[bool] = None						,	lowercase_				:Optional[float] = None						,	lowercase_				:Optional[bool] = None						,	lowercase_				:Optional[Union[float, List[float]]] = None						,	lowercase_				:Optional[Union[float, List[float]]] = None						,	lowercase_				:Optional[Union[str, TensorType]] = None						,	lowercase_				:Union[str, ChannelDimension] = ChannelDimension.FIRST						,	**lowercase_				:str						,	)->							List[str]:
    A__    =      do_resize if do_resize is not None else self.do_resize
    A__    =      size if size is not None else self.size
    A__    =      get_size_dict(a_						,	default_to_square=a_							)
    A__    =      resample if resample is not None else self.resample
    A__    =      do_center_crop if do_center_crop is not None else self.do_center_crop
    A__    =      crop_size if crop_size is not None else self.crop_size
    A__    =      get_size_dict(a_							)
    A__    =      do_rescale if do_rescale is not None else self.do_rescale
    A__    =      rescale_factor if rescale_factor is not None else self.rescale_factor
    A__    =      do_normalize if do_normalize is not None else self.do_normalize
    A__    =      image_mean if image_mean is not None else self.image_mean
    A__    =      image_std if image_std is not None else self.image_std

    A__    =      make_list_of_images(a_							)

    if not valid_images(a_							):
       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.
    A__    =      [to_numpy_array(a_							) for image in images]

    if do_resize:
       A__    =      [self.resize(image=a_						,	size=a_						,	resample=a_							) for image in images]

    if do_center_crop:
       A__    =      [self.center_crop(image=a_						,	size=a_							) for image in images]

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

    if do_normalize:
       A__    =      [self.normalize(image=a_						,	mean=a_						,	std=a_							) for image in images]

    A__    =      [to_channel_dimension_format(a_						,	a_							) for image in images]

    A__    =      {"pixel_values": images}
    return BatchFeature(data=a_						,	tensor_type=a_							)










'''simple docstring'''

import json
import os
import unittest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class        UpperCAmelCase     (	UpperCamelCase__      ,	unittest.TestCase    ):
 __lowercase       		=    CLIPTokenizer
 __lowercase       		=    CLIPTokenizerFast
 __lowercase       		=    True
 __lowercase       		=    {}
 __lowercase       		=    False
 def 					UpperCAmelCase_							(    self				:Optional[int]							)->							Optional[Any]:
     super().setUp()

     # fmt: off
     A__    =      ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
     # fmt: on
     A__    =      dict(zip(lowercase_						,	range(len(lowercase_							)							)							)							)
     A__    =      ["#version: 0.2", "l o", "lo w</w>", "e r</w>"]
     A__    =      {"unk_token": "<unk>"}

     A__    =      os.path.join(self.tmpdirname						,	VOCAB_FILES_NAMES["vocab_file"]							)
     A__    =      os.path.join(self.tmpdirname						,	VOCAB_FILES_NAMES["merges_file"]							)
     with open(self.vocab_file						,	"w"						,	encoding="utf-8"							) as fp:
         fp.write(json.dumps(lowercase_							) + "\n"							)
     with open(self.merges_file						,	"w"						,	encoding="utf-8"							) as fp:
         fp.write("\n".join(lowercase_							)							)
 def 					UpperCAmelCase_							(    self				:Optional[int]						,	**lowercase_				:List[str]							)->							str:
     kwargs.update(self.special_tokens_map							)
     return CLIPTokenizer.from_pretrained(self.tmpdirname						,	**lowercase_							)
 def 					UpperCAmelCase_							(    self				:Optional[int]						,	**lowercase_				:Optional[int]							)->							Tuple:
     kwargs.update(self.special_tokens_map							)
     return CLIPTokenizerFast.from_pretrained(self.tmpdirname						,	**lowercase_							)
 def 					UpperCAmelCase_							(    self				:Optional[int]						,	lowercase_				:List[Any]							)->							List[str]:
     A__    =      "lower newer"
     A__    =      "lower newer"
     return input_text, output_text
 def 					UpperCAmelCase_							(    self				:int							)->							List[str]:
     A__    =      CLIPTokenizer(self.vocab_file						,	self.merges_file						,	**self.special_tokens_map							)
     A__    =      "lower newer"
     A__    =      ["lo", "w", "er</w>", "n", "e", "w", "er</w>"]
     A__    =      tokenizer.tokenize(lowercase_							)
     self.assertListEqual(lowercase_						,	lowercase_							)

     A__    =      tokens + [tokenizer.unk_token]
     A__    =      [10, 2, 16, 9, 3, 2, 16, 20]
     self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_							)						,	lowercase_							)
 @require_ftfy
 def 					UpperCAmelCase_							(    self				:Dict							)->							str:
     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"							):
             A__    =      self.tokenizer_class.from_pretrained(lowercase_						,	**lowercase_							)
             A__    =      self.rust_tokenizer_class.from_pretrained(lowercase_						,	**lowercase_							)

             A__    =      "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d."
             A__    =      tokenizer_s.tokenize(lowercase_							)
             A__    =      tokenizer_r.tokenize(lowercase_							)

             self.assertListEqual(lowercase_						,	lowercase_							)

             # Test that the tokenization is identical on an example containing a character (Latin Small Letter A
             # with Tilde) encoded in 2 different ways
             A__    =      "xa\u0303y" + " " + "x\xe3y"
             A__    =      tokenizer_s.tokenize(lowercase_							)
             A__    =      tokenizer_r.tokenize(lowercase_							)

             self.assertListEqual(lowercase_						,	lowercase_							)

             # Test that the tokenization is identical on unicode of space type
             A__    =      [
                 "\u0009",  # (horizontal tab, '\t')
                 "\u000B",  # (vertical tab)
                 "\u000C",  # (form feed)
                 "\u0020",  # (space, ' ')
                 "\u200E",  # (left-to-right mark):w
                 "\u200F",  # (right-to-left mark)
             ]
             for unicode_seq in spaces_unicodes:
                 A__    =      tokenizer_s.tokenize(lowercase_							)
                 A__    =      tokenizer_r.tokenize(lowercase_							)

                 self.assertListEqual(lowercase_						,	lowercase_							)

             # Test that the tokenization is identical on unicode of line break type
             A__    =      [
                 "\u000A",  # (line feed, '\n')
                 "\r\n",  # (carriage return and line feed, '\r\n')
                 "\u000D",  # (carriage return, '\r')
                 "\r",  # (carriage return, '\r')
                 "\u000D",  # (carriage return, '\r')
                 "\u2028",  # (line separator)
                 "\u2029",  # (paragraph separator)
                 # "\u0085", # (next line)
             ]

             # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms
             # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a
             # space (and thus into an empty list).

             for unicode_seq in line_break_unicodes:
                 A__    =      tokenizer_s.tokenize(lowercase_							)
                 A__    =      tokenizer_r.tokenize(lowercase_							)

                 self.assertListEqual(lowercase_						,	lowercase_							)
 def 					UpperCAmelCase_							(    self				:Optional[int]							)->							Optional[Any]:
     # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space`
     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"							):
             A__    =      "hello"  # `hello` is a token in the vocabulary of `pretrained_name`
             A__    =      F"{text_of_1_token} {text_of_1_token}"

             A__    =      self.rust_tokenizer_class.from_pretrained(
                 lowercase_						,	use_fast=lowercase_						,	)
             A__    =      tokenizer_r(lowercase_						,	return_offsets_mapping=lowercase_						,	add_special_tokens=lowercase_							)
             self.assertEqual(encoding.offset_mapping[0]						,	(0, len(lowercase_							))							)
             self.assertEqual(
                 encoding.offset_mapping[1]						,	(len(lowercase_							) + 1, len(lowercase_							) + 1 + len(lowercase_							))						,	)

             A__    =      F" {text}"

             A__    =      self.rust_tokenizer_class.from_pretrained(
                 lowercase_						,	use_fast=lowercase_						,	)
             A__    =      tokenizer_r(lowercase_						,	return_offsets_mapping=lowercase_						,	add_special_tokens=lowercase_							)
             self.assertEqual(encoding.offset_mapping[0]						,	(1, 1 + len(lowercase_							))							)
             self.assertEqual(
                 encoding.offset_mapping[1]						,	(1 + len(lowercase_							) + 1, 1 + len(lowercase_							) + 1 + len(lowercase_							))						,	)
 def 					UpperCAmelCase_							(    self				:Dict							)->							Optional[Any]:
     # Test related to the breaking change introduced in transformers v4.17.0
     # We need to check that an error in raised when the user try to load a previous version of the tokenizer.
     with self.assertRaises(lowercase_							) as context:
         self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer"							)

     self.assertTrue(
         context.exception.args[0].startswith(
             "The `backend_tokenizer` provided does not match the expected format."							)							)
 @require_ftfy
 def 					UpperCAmelCase_							(    self				:str							)->							Any:
     super().test_tokenization_python_rust_equals()



 def 					UpperCAmelCase_							(    self				:Optional[int]							)->							Union[str, Any]:
     # CLIP always lower cases letters
     pass



