'''simple docstring'''




import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
__UpperCAmelCase												={"LayoutLMv2Config", "LayoutLMv3Config"}




@is_pipeline_test
class    a__				(       unittest.TestCase			):
     lowerCamelCase  :					Tuple							=MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
     lowerCamelCase  :					List[Any]							=TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

     if model_mapping is not None:
          lowerCamelCase  :					int							={config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
     if tf_model_mapping is not None:
          lowerCamelCase  :					Tuple							={
              config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
          }






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  pipeline(
             task='''text-classification'''  ,    model='''hf-internal-testing/tiny-random-distilbert'''  ,    framework='''pt'''   )

         __lowerCamelCase          =  text_classifier('''This is great !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''LABEL_0''', '''score''': 0.5_04}]   )

         __lowerCamelCase          =  text_classifier('''This is great !'''  ,    top_k=2   )
         self.assertEqual(
             nested_simplify(a   )  ,    [{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}]   )

         __lowerCamelCase          =  text_classifier(['''This is great !''', '''This is bad''']  ,    top_k=2   )
         self.assertEqual(
             nested_simplify(a   )  ,    [
                 [{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}],
                 [{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}],
             ]  ,    )

         __lowerCamelCase          =  text_classifier('''This is great !'''  ,    top_k=1   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''LABEL_0''', '''score''': 0.5_04}]   )

         # Legacy behavior
         __lowerCamelCase          =  text_classifier('''This is great !'''  ,    return_all_scores=a   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''LABEL_0''', '''score''': 0.5_04}]   )

         __lowerCamelCase          =  text_classifier('''This is great !'''  ,    return_all_scores=a   )
         self.assertEqual(
             nested_simplify(a   )  ,    [[{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}]]   )

         __lowerCamelCase          =  text_classifier(['''This is great !''', '''Something else''']  ,    return_all_scores=a   )
         self.assertEqual(
             nested_simplify(a   )  ,    [
                 [{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}],
                 [{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}],
             ]  ,    )

         __lowerCamelCase          =  text_classifier(['''This is great !''', '''Something else''']  ,    return_all_scores=a   )
         self.assertEqual(
             nested_simplify(a   )  ,    [
                 {'''label''': '''LABEL_0''', '''score''': 0.5_04},
                 {'''label''': '''LABEL_0''', '''score''': 0.5_04},
             ]  ,    )






     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         import torch

         __lowerCamelCase          =  pipeline(
             task='''text-classification'''  ,    model='''hf-internal-testing/tiny-random-distilbert'''  ,    framework='''pt'''  ,    device=torch.device('''cpu'''   )  ,    )

         __lowerCamelCase          =  text_classifier('''This is great !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''LABEL_0''', '''score''': 0.5_04}]   )






     @require_tf
     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  pipeline(
             task='''text-classification'''  ,    model='''hf-internal-testing/tiny-random-distilbert'''  ,    framework='''tf'''   )

         __lowerCamelCase          =  text_classifier('''This is great !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''LABEL_0''', '''score''': 0.5_04}]   )






     @slow
     @require_torch
     def        SCREAMING_SNAKE_CASE__       (			self		:		Any   ):





         """simple docstring"""



         __lowerCamelCase          =  pipeline('''text-classification'''   )

         __lowerCamelCase          =  text_classifier('''This is great !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''POSITIVE''', '''score''': 1.0}]   )
         __lowerCamelCase          =  text_classifier('''This is bad !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''NEGATIVE''', '''score''': 1.0}]   )
         __lowerCamelCase          =  text_classifier('''Birds are a type of animal'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''POSITIVE''', '''score''': 0.9_88}]   )






     @slow
     @require_tf
     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  pipeline('''text-classification'''  ,    framework='''tf'''   )

         __lowerCamelCase          =  text_classifier('''This is great !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''POSITIVE''', '''score''': 1.0}]   )
         __lowerCamelCase          =  text_classifier('''This is bad !'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''NEGATIVE''', '''score''': 1.0}]   )
         __lowerCamelCase          =  text_classifier('''Birds are a type of animal'''   )
         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': '''POSITIVE''', '''score''': 0.9_88}]   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]  ,    a		:		Optional[Any]  ,    a		:		Dict  ,    a		:		Union[str, Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  TextClassificationPipeline(model=a  ,    tokenizer=a   )
         return text_classifier, ["HuggingFace is in", "This is another test"]






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple  ,    a		:		Optional[Any]  ,    a		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  text_classifier.model
         # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
         __lowerCamelCase          =  '''HuggingFace is in'''
         __lowerCamelCase          =  text_classifier(a   )

         self.assertEqual(nested_simplify(a   )  ,    [{'''label''': ANY(a   ), '''score''': ANY(a   )}]   )
         self.assertTrue(outputs[0]['''label'''] in model.config.idalabel.values()   )

         __lowerCamelCase          =  ['''HuggingFace is in ''', '''Paris is in France''']
         __lowerCamelCase          =  text_classifier(a   )
         self.assertEqual(
             nested_simplify(a   )  ,    [{'''label''': ANY(a   ), '''score''': ANY(a   )}, {'''label''': ANY(a   ), '''score''': ANY(a   )}]  ,    )
         self.assertTrue(outputs[0]['''label'''] in model.config.idalabel.values()   )
         self.assertTrue(outputs[1]['''label'''] in model.config.idalabel.values()   )

         # Forcing to get all results with `top_k=None`
         # This is NOT the legacy format
         __lowerCamelCase          =  text_classifier(a  ,    top_k=a   )
         __lowerCamelCase          =  len(model.config.idalabel.values()   )
         self.assertEqual(
             nested_simplify(a   )  ,    [[{'''label''': ANY(a   ), '''score''': ANY(a   )}] * N, [{'''label''': ANY(a   ), '''score''': ANY(a   )}] * N]  ,    )

         __lowerCamelCase          =  {'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
         __lowerCamelCase          =  text_classifier(a   )
         self.assertEqual(
             nested_simplify(a   )  ,    {'''label''': ANY(a   ), '''score''': ANY(a   )}  ,    )
         self.assertTrue(outputs['''label'''] in model.config.idalabel.values()   )

         # This might be used a text pair, but tokenizer + pipe interaction
         # makes it hard to understand that it's not using the pair properly
         # https://github.com/huggingface/transformers/issues/17305
         # We disabled this usage instead as it was outputting wrong outputs.
         __lowerCamelCase          =  [['''HuggingFace is in ''', '''Paris is in France''']]
         with self.assertRaises(a   ):
             text_classifier(a   )

         # This used to be valid for doing text pairs
         # We're keeping it working because of backward compatibility
         __lowerCamelCase          =  text_classifier([[['''HuggingFace is in ''', '''Paris is in France''']]]   )
         self.assertEqual(
             nested_simplify(a   )  ,    [{'''label''': ANY(a   ), '''score''': ANY(a   )}]  ,    )
         self.assertTrue(outputs[0]['''label'''] in model.config.idalabel.values()   )

'''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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
  import PIL


__UpperCAmelCase												=logging.get_logger(__name__)




class    a__				(       UpperCAmelCase__			):
     lowerCamelCase  :					Dict							=["pixel_values"]






     def __init__(			self		:		List[str]  ,    a		:		bool = True  ,    a		:		Dict[str, int] = None  ,    a		:		int = 0.9  ,    a		:		PILImageResampling = PILImageResampling.BICUBIC  ,    a		:		bool = True  ,    a		:		Dict[str, int] = None  ,    a		:		Union[int, float] = 1 / 2_55  ,    a		:		bool = True  ,    a		:		bool = True  ,    a		:		Optional[Union[float, List[float]]] = None  ,    a		:		Optional[Union[float, List[float]]] = None  ,    **a		:		Dict  ,    ):





         """simple docstring"""



         super().__init__(**a   )
         __lowerCamelCase          =  size if size is not None else {'''shortest_edge''': 2_24}
         __lowerCamelCase          =  get_size_dict(a  ,    default_to_square=a   )
         __lowerCamelCase          =  crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
         __lowerCamelCase          =  get_size_dict(a  ,    param_name='''crop_size'''   )

         __lowerCamelCase          =  do_resize
         __lowerCamelCase          =  size
         __lowerCamelCase          =  crop_pct
         __lowerCamelCase          =  resample
         __lowerCamelCase          =  do_center_crop
         __lowerCamelCase          =  crop_size
         __lowerCamelCase          =  do_rescale
         __lowerCamelCase          =  rescale_factor
         __lowerCamelCase          =  do_normalize
         __lowerCamelCase          =  image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         __lowerCamelCase          =  image_std if image_std is not None else IMAGENET_DEFAULT_STD






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any  ,    a		:		np.ndarray  ,    a		:		Dict[str, int]  ,    a		:		Optional[float] = None  ,    a		:		PILImageResampling = PILImageResampling.BICUBIC  ,    a		:		Optional[Union[str, ChannelDimension]] = None  ,    **a		:		List[str]  ,    ):





         """simple docstring"""



         __lowerCamelCase          =  get_size_dict(a  ,    default_to_square=a   )
         if "shortest_edge" not in size and ("height" not in size or "width" not in size):
             raise ValueError(f"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"""   )
         if crop_pct is not None:
             if "shortest_edge" in size:
                 __lowerCamelCase          =  int(size['''shortest_edge'''] / crop_pct   )
             elif "height" in size and "width" in size:
                 if size["height"] == size["width"]:
                     __lowerCamelCase          =  int(size['''height'''] / crop_pct   )
                 else:
                     __lowerCamelCase          =  (int(size['''height'''] / crop_pct   ), int(size['''width'''] / crop_pct   ))
             else:
                 raise ValueError('''Invalid size for resize: {}'''.format(a   )   )

             __lowerCamelCase          =  get_resize_output_image_size(a  ,    size=a  ,    default_to_square=a   )
         else:
             if "shortest_edge" in size:
                 __lowerCamelCase          =  get_resize_output_image_size(a  ,    size=size['''shortest_edge''']  ,    default_to_square=a   )
             elif "height" in size and "width" in size:
                 __lowerCamelCase          =  (size['''height'''], size['''width'''])
             else:
                 raise ValueError('''Invalid size for resize: {}'''.format(a   )   )

         return resize(a  ,    size=a  ,    resample=a  ,    data_format=a  ,    **a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		np.ndarray  ,    a		:		Dict[str, int]  ,    a		:		Optional[Union[str, ChannelDimension]] = None  ,    **a		:		Dict  ,    ):





         """simple docstring"""



         __lowerCamelCase          =  get_size_dict(a   )
         if "height" not in size or "width" not in size:
             raise ValueError(f"""size must contain 'height' and 'width' as keys. Got {size.keys()}"""   )
         return center_crop(a  ,    size=(size['''height'''], size['''width'''])  ,    data_format=a  ,    **a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    a		:		np.ndarray  ,    a		:		Union[int, float]  ,    a		:		Optional[Union[str, ChannelDimension]] = None  ,    **a		:		Union[str, Any]  ,    ):





         """simple docstring"""



         return rescale(a  ,    scale=a  ,    data_format=a  ,    **a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]  ,    a		:		np.ndarray  ,    a		:		Union[float, List[float]]  ,    a		:		Union[float, List[float]]  ,    a		:		Optional[Union[str, ChannelDimension]] = None  ,    **a		:		Any  ,    ):





         """simple docstring"""



         return normalize(a  ,    mean=a  ,    std=a  ,    data_format=a  ,    **a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]  ,    a		:		ImageInput  ,    a		:		bool = None  ,    a		:		Dict[str, int] = None  ,    a		:		int = None  ,    a		:		PILImageResampling = None  ,    a		:		bool = None  ,    a		:		Dict[str, int] = None  ,    a		:		bool = None  ,    a		:		float = None  ,    a		:		bool = None  ,    a		:		Optional[Union[float, List[float]]] = None  ,    a		:		Optional[Union[float, List[float]]] = None  ,    a		:		Optional[Union[str, TensorType]] = None  ,    a		:		ChannelDimension = ChannelDimension.FIRST  ,    **a		:		Tuple  ,    ):





         """simple docstring"""



         __lowerCamelCase          =  do_resize if do_resize is not None else self.do_resize
         __lowerCamelCase          =  crop_pct if crop_pct is not None else self.crop_pct
         __lowerCamelCase          =  resample if resample is not None else self.resample
         __lowerCamelCase          =  do_center_crop if do_center_crop is not None else self.do_center_crop
         __lowerCamelCase          =  do_rescale if do_rescale is not None else self.do_rescale
         __lowerCamelCase          =  rescale_factor if rescale_factor is not None else self.rescale_factor
         __lowerCamelCase          =  do_normalize if do_normalize is not None else self.do_normalize
         __lowerCamelCase          =  image_mean if image_mean is not None else self.image_mean
         __lowerCamelCase          =  image_std if image_std is not None else self.image_std

         __lowerCamelCase          =  size if size is not None else self.size
         __lowerCamelCase          =  get_size_dict(a  ,    default_to_square=a   )
         __lowerCamelCase          =  crop_size if crop_size is not None else self.crop_size
         __lowerCamelCase          =  get_size_dict(a  ,    param_name='''crop_size'''   )

         __lowerCamelCase          =  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 or resample is None:
             raise ValueError('''Size and resample must be specified if do_resize is True.'''   )

         if do_center_crop and crop_pct is None:
             raise ValueError('''Crop_pct 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.
         __lowerCamelCase          =  [to_numpy_array(a   ) for image in images]

         if do_resize:
             __lowerCamelCase          =  [self.resize(image=a  ,    size=a  ,    crop_pct=a  ,    resample=a   ) for image in images]

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

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

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

         __lowerCamelCase          =  [to_channel_dimension_format(a  ,    a   ) for image in images]

         __lowerCamelCase          =  {'''pixel_values''': images}
         return BatchFeature(data=a  ,    tensor_type=a   )
