





'''simple docstring'''


import unittest

from transformers import LiltConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     LiltForQuestionAnswering,
     LiltForSequenceClassification,
     LiltForTokenClassification,
     LiltModel,
 )
 from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST
class 				a_       :





     def __init__(			self		: Optional[Any]     ,				lowercase		: Optional[Any]     ,				lowercase		: Optional[int]=13     ,				lowercase		: List[Any]=7     ,				lowercase		: int=True     ,				lowercase		: Optional[Any]=True     ,				lowercase		: Optional[int]=True     ,				lowercase		: Tuple=True     ,				lowercase		: Tuple=99     ,				lowercase		: Optional[int]=24     ,				lowercase		: str=2     ,				lowercase		: List[Any]=6     ,				lowercase		: Optional[Any]=37     ,				lowercase		: Optional[Any]="gelu"     ,				lowercase		: Any=0.1     ,				lowercase		: Optional[Any]=0.1     ,				lowercase		: List[Any]=512     ,				lowercase		: List[Any]=16     ,				lowercase		: Optional[Any]=2     ,				lowercase		: Any=0.02     ,				lowercase		: Tuple=3     ,				lowercase		: Dict=None     ,				lowercase		: Optional[Any]=1_000     ,				):





        """simple docstring"""




        lowercase_      :Union[str, Any]         =			parent
        lowercase_      :List[Any]         =			batch_size
        lowercase_      :int         =			seq_length
        lowercase_      :int         =			is_training
        lowercase_      :Optional[Any]         =			use_input_mask
        lowercase_      :Union[str, Any]         =			use_token_type_ids
        lowercase_      :str         =			use_labels
        lowercase_      :List[Any]         =			vocab_size
        lowercase_      :List[Any]         =			hidden_size
        lowercase_      :int         =			num_hidden_layers
        lowercase_      :Dict         =			num_attention_heads
        lowercase_      :Any         =			intermediate_size
        lowercase_      :Optional[Any]         =			hidden_act
        lowercase_      :Any         =			hidden_dropout_prob
        lowercase_      :List[Any]         =			attention_probs_dropout_prob
        lowercase_      :Dict         =			max_position_embeddings
        lowercase_      :str         =			type_vocab_size
        lowercase_      :List[str]         =			type_sequence_label_size
        lowercase_      :Union[str, Any]         =			initializer_range
        lowercase_      :Union[str, Any]         =			num_labels
        lowercase_      :int         =			scope
        lowercase_      :Tuple         =			range_bbox





     def 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        lowercase_      :Any         =			ids_tensor([self.batch_size, self.seq_length]     ,				self.vocab_size						)

        lowercase_      :List[Any]         =			ids_tensor([self.batch_size, self.seq_length, 4]     ,				self.range_bbox						)
        # Ensure that bbox is legal
        for i in range(bbox.shape[0]						):
           for j in range(bbox.shape[1]						):
              if bbox[i, j, 3] < bbox[i, j, 1]:
                 lowercase_      :Tuple         =			bbox[i, j, 3]
                 lowercase_      :Optional[int]         =			bbox[i, j, 1]
                 lowercase_      :Union[str, Any]         =			t
              if bbox[i, j, 2] < bbox[i, j, 0]:
                 lowercase_      :str         =			bbox[i, j, 2]
                 lowercase_      :Optional[int]         =			bbox[i, j, 0]
                 lowercase_      :Dict         =			t

        lowercase_      :Any         =			None
        if self.use_input_mask:
           lowercase_      :List[str]         =			ids_tensor([self.batch_size, self.seq_length]     ,				vocab_size=2						)

        lowercase_      :Tuple         =			None
        if self.use_token_type_ids:
           lowercase_      :List[Any]         =			ids_tensor([self.batch_size, self.seq_length]     ,				self.type_vocab_size						)

        lowercase_      :Optional[Any]         =			None
        lowercase_      :Dict         =			None
        if self.use_labels:
           lowercase_      :str         =			ids_tensor([self.batch_size]     ,				self.type_sequence_label_size						)
           lowercase_      :List[Any]         =			ids_tensor([self.batch_size, self.seq_length]     ,				self.num_labels						)

        lowercase_      :str         =			self.get_config()

        return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels





     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        return LiltConfig(
            vocab_size=self.vocab_size     ,				hidden_size=self.hidden_size     ,				num_hidden_layers=self.num_hidden_layers     ,				num_attention_heads=self.num_attention_heads     ,				intermediate_size=self.intermediate_size     ,				hidden_act=self.hidden_act     ,				hidden_dropout_prob=self.hidden_dropout_prob     ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,				max_position_embeddings=self.max_position_embeddings     ,				type_vocab_size=self.type_vocab_size     ,				initializer_range=self.initializer_range     ,				)





     def 							lowercase__				(			self		: Union[str, Any]     ,				lowercase		: Union[str, Any]     ,				lowercase		: Tuple     ,				lowercase		: Optional[Any]     ,				lowercase		: Optional[Any]     ,				lowercase		: Any     ,				lowercase		: Union[str, Any]     ,				lowercase		: List[Any]     ,				):





        """simple docstring"""




        lowercase_      :List[Any]         =			LiltModel(config=lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :Dict         =			model(lowercase     ,				bbox=lowercase     ,				attention_mask=lowercase     ,				token_type_ids=lowercase						)
        lowercase_      :Optional[int]         =			model(lowercase     ,				bbox=lowercase     ,				token_type_ids=lowercase						)
        lowercase_      :List[Any]         =			model(lowercase     ,				bbox=lowercase						)

        self.parent.assertEqual(result.last_hidden_state.shape     ,				(self.batch_size, self.seq_length, self.hidden_size)						)
        self.parent.assertEqual(result.pooler_output.shape     ,				(self.batch_size, self.hidden_size)						)





     def 							lowercase__				(			self		: List[str]     ,				lowercase		: Dict     ,				lowercase		: Dict     ,				lowercase		: str     ,				lowercase		: Optional[int]     ,				lowercase		: Union[str, Any]     ,				lowercase		: List[Any]     ,				lowercase		: Union[str, Any]     ,				):





        """simple docstring"""




        lowercase_      :Tuple         =			self.num_labels
        lowercase_      :Optional[Any]         =			LiltForTokenClassification(config=lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :List[str]         =			model(
            lowercase     ,				bbox=lowercase     ,				attention_mask=lowercase     ,				token_type_ids=lowercase     ,				labels=lowercase						)
        self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.seq_length, self.num_labels)						)





     def 							lowercase__				(			self		: Optional[int]     ,				lowercase		: Tuple     ,				lowercase		: int     ,				lowercase		: Union[str, Any]     ,				lowercase		: Union[str, Any]     ,				lowercase		: int     ,				lowercase		: int     ,				lowercase		: Tuple     ,				):





        """simple docstring"""




        lowercase_      :Tuple         =			LiltForQuestionAnswering(config=lowercase						)
        model.to(lowercase						)
        model.eval()
        lowercase_      :int         =			model(
            lowercase     ,				bbox=lowercase     ,				attention_mask=lowercase     ,				token_type_ids=lowercase     ,				start_positions=lowercase     ,				end_positions=lowercase     ,				)
        self.parent.assertEqual(result.start_logits.shape     ,				(self.batch_size, self.seq_length)						)
        self.parent.assertEqual(result.end_logits.shape     ,				(self.batch_size, self.seq_length)						)







     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        lowercase_      :List[str]         =			self.prepare_config_and_inputs()
        (
            (
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							(
            lowercase_
        )      ,							
        )      :Dict         =			config_and_inputs
        lowercase_      :Union[str, Any]         =			{
            "input_ids": input_ids,
            "bbox": bbox,
            "token_type_ids": token_type_ids,
            "attention_mask": input_mask,
        }
        return config, inputs_dict







@require_torch
class 				a_       (    _lowerCAmelCase     ,						_lowerCAmelCase     ,						_lowerCAmelCase     ,						unittest.TestCase							):
     __A								=      (
         (
             LiltModel,
             LiltForSequenceClassification,
             LiltForTokenClassification,
             LiltForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     __A								=      (
         {
             "feature-extraction": LiltModel,
             "question-answering": LiltForQuestionAnswering,
             "text-classification": LiltForSequenceClassification,
             "token-classification": LiltForTokenClassification,
             "zero-shot": LiltForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     __A								=      False
     __A								=      False





     def 							lowercase__				(			self		: List[str]     ,				lowercase		: Union[str, Any]     ,				lowercase		: str     ,				lowercase		: Any     ,				lowercase		: List[str]     ,				lowercase		: Optional[Any]						):





        """simple docstring"""




        return True





     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        lowercase_      :List[str]         =			LiltModelTester(self						)
        lowercase_      :str         =			ConfigTester(self     ,				config_class=lowercase     ,				hidden_size=37						)





     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        self.config_tester.run_common_tests()





     def 							lowercase__				(			self		: Tuple						):





        """simple docstring"""




        lowercase_      :List[Any]         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase						)





     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




        lowercase_      :List[Any]         =			self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
           lowercase_      :Tuple         =			type
           self.model_tester.create_and_check_model(*lowercase						)





     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        lowercase_      :List[str]         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowercase						)





     def 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        lowercase_      :int         =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowercase						)







     @slow
     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




        for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase_      :Dict         =			LiltModel.from_pretrained(lowercase						)
           self.assertIsNotNone(lowercase						)







@require_torch
@slow
class 				a_       (    unittest.TestCase							):





     def 							lowercase__				(			self		: List[str]						):





        """simple docstring"""




        lowercase_      :List[str]         =			LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base"						).to(lowercase						)

        lowercase_      :List[str]         =			torch.tensor([[1, 2]]     ,				device=lowercase						)
        lowercase_      :Any         =			torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]     ,				device=lowercase						)

        # forward pass
        with torch.no_grad():
           lowercase_      :int         =			model(input_ids=lowercase     ,				bbox=lowercase						)

        lowercase_      :Optional[int]         =			torch.Size([1, 2, 768]						)
        lowercase_      :List[Any]         =			torch.tensor(
            [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]]     ,				device=lowercase     ,				)

        self.assertTrue(outputs.last_hidden_state.shape     ,				lowercase						)
        self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3]     ,				lowercase     ,				atol=1e-3						)						)









'''simple docstring'''


from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

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,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
 import PIL

lowerCAmelCase :					Any 							=logging.get_logger(__name__)
def 							UpperCAmelCase_  (						__lowerCamelCase : List[str]			):
   if isinstance(__lowerCamelCase     ,(list, tuple)			) and isinstance(videos[0]     ,(list, tuple)			) and is_valid_image(videos[0][0]			):
      return videos

   elif isinstance(__lowerCamelCase     ,(list, tuple)			) and is_valid_image(videos[0]			):
      return [videos]

   elif is_valid_image(__lowerCamelCase			):
      return [[videos]]

   raise ValueError(F'Could not make batched video from {videos}'			)


class 				a_       (    _lowerCAmelCase							):
     __A								=      ["pixel_values"]





     def __init__(			self		: List[str]     ,				lowercase		: bool = True     ,				lowercase		: Dict[str, int] = None     ,				lowercase		: PILImageResampling = PILImageResampling.BILINEAR     ,				lowercase		: bool = True     ,				lowercase		: Dict[str, int] = None     ,				lowercase		: bool = True     ,				lowercase		: Union[int, float] = 1 / 255     ,				lowercase		: bool = True     ,				lowercase		: bool = True     ,				lowercase		: Optional[Union[float, List[float]]] = None     ,				lowercase		: Optional[Union[float, List[float]]] = None     ,				**lowercase		: Tuple     ,				):





        """simple docstring"""




        super().__init__(**lowercase						)
        lowercase_      :Any         =			size if size is not None else {"shortest_edge": 256}
        lowercase_      :int         =			get_size_dict(lowercase     ,				default_to_square=lowercase						)
        lowercase_      :str         =			crop_size if crop_size is not None else {"height": 224, "width": 224}
        lowercase_      :List[str]         =			get_size_dict(lowercase     ,				param_name="crop_size"						)

        lowercase_      :List[str]         =			do_resize
        lowercase_      :Any         =			size
        lowercase_      :Union[str, Any]         =			do_center_crop
        lowercase_      :Union[str, Any]         =			crop_size
        lowercase_      :Optional[Any]         =			resample
        lowercase_      :List[str]         =			do_rescale
        lowercase_      :List[Any]         =			rescale_factor
        lowercase_      :Dict         =			offset
        lowercase_      :Optional[Any]         =			do_normalize
        lowercase_      :Dict         =			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        lowercase_      :Optional[int]         =			image_std if image_std is not None else IMAGENET_STANDARD_STD





     def 							lowercase__				(			self		: Union[str, Any]     ,				lowercase		: np.ndarray     ,				lowercase		: Dict[str, int]     ,				lowercase		: PILImageResampling = PILImageResampling.BILINEAR     ,				lowercase		: Optional[Union[str, ChannelDimension]] = None     ,				**lowercase		: Optional[Any]     ,				):





        """simple docstring"""




        lowercase_      :List[Any]         =			get_size_dict(lowercase     ,				default_to_square=lowercase						)
        if "shortest_edge" in size:
           lowercase_      :int         =			get_resize_output_image_size(lowercase     ,				size["shortest_edge"]     ,				default_to_square=lowercase						)
        elif "height" in size and "width" in size:
           lowercase_      :Union[str, Any]         =			(size["height"], size["width"])
        else:
           raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'						)
        return resize(lowercase     ,				size=lowercase     ,				resample=lowercase     ,				data_format=lowercase     ,				**lowercase						)





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





        """simple docstring"""




        lowercase_      :Any         =			get_size_dict(lowercase						)
        if "height" not in size or "width" not in size:
           raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}'						)
        return center_crop(lowercase     ,				size=(size["height"], size["width"])     ,				data_format=lowercase     ,				**lowercase						)





     def 							lowercase__				(			self		: List[str]     ,				lowercase		: np.ndarray     ,				lowercase		: Union[int, float]     ,				lowercase		: bool = True     ,				lowercase		: Optional[Union[str, ChannelDimension]] = None     ,				**lowercase		: List[str]     ,				):





        """simple docstring"""




        lowercase_      :List[str]         =			image.astype(np.floataa						)
        if offset:
           lowercase_      :List[str]         =			image - (scale / 2)
        return rescale(lowercase     ,				scale=lowercase     ,				data_format=lowercase     ,				**lowercase						)





     def 							lowercase__				(			self		: Tuple     ,				lowercase		: np.ndarray     ,				lowercase		: Union[float, List[float]]     ,				lowercase		: Union[float, List[float]]     ,				lowercase		: Optional[Union[str, ChannelDimension]] = None     ,				**lowercase		: Dict     ,				):





        """simple docstring"""




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





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





        """simple docstring"""




        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_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."						)

        if offset and not do_rescale:
           raise ValueError("For offset, do_rescale must also be set to True."						)

        # All transformations expect numpy arrays.
        lowercase_      :Optional[int]         =			to_numpy_array(lowercase						)

        if do_resize:
           lowercase_      :Tuple         =			self.resize(image=lowercase     ,				size=lowercase     ,				resample=lowercase						)

        if do_center_crop:
           lowercase_      :Any         =			self.center_crop(lowercase     ,				size=lowercase						)

        if do_rescale:
           lowercase_      :Optional[Any]         =			self.rescale(image=lowercase     ,				scale=lowercase     ,				offset=lowercase						)

        if do_normalize:
           lowercase_      :Tuple         =			self.normalize(image=lowercase     ,				mean=lowercase     ,				std=lowercase						)

        lowercase_      :Optional[Any]         =			to_channel_dimension_format(lowercase     ,				lowercase						)
        return image







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





        """simple docstring"""




        lowercase_      :str         =			do_resize if do_resize is not None else self.do_resize
        lowercase_      :Optional[Any]         =			resample if resample is not None else self.resample
        lowercase_      :Tuple         =			do_center_crop if do_center_crop is not None else self.do_center_crop
        lowercase_      :Dict         =			do_rescale if do_rescale is not None else self.do_rescale
        lowercase_      :Optional[int]         =			rescale_factor if rescale_factor is not None else self.rescale_factor
        lowercase_      :Dict         =			offset if offset is not None else self.offset
        lowercase_      :Tuple         =			do_normalize if do_normalize is not None else self.do_normalize
        lowercase_      :int         =			image_mean if image_mean is not None else self.image_mean
        lowercase_      :Optional[int]         =			image_std if image_std is not None else self.image_std

        lowercase_      :int         =			size if size is not None else self.size
        lowercase_      :Optional[int]         =			get_size_dict(lowercase     ,				default_to_square=lowercase						)
        lowercase_      :List[Any]         =			crop_size if crop_size is not None else self.crop_size
        lowercase_      :List[str]         =			get_size_dict(lowercase     ,				param_name="crop_size"						)

        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."						)

        lowercase_      :List[str]         =			make_batched(lowercase						)

        lowercase_      :List[Any]         =			[
            [
                self._preprocess_image(
                    image=lowercase     ,				do_resize=lowercase     ,				size=lowercase     ,				resample=lowercase     ,				do_center_crop=lowercase     ,				crop_size=lowercase     ,				do_rescale=lowercase     ,				rescale_factor=lowercase     ,				offset=lowercase     ,				do_normalize=lowercase     ,				image_mean=lowercase     ,				image_std=lowercase     ,				data_format=lowercase     ,				)
                for img in video
            ]
            for video in videos
        ]

        lowercase_      :Optional[int]         =			{"pixel_values": videos}
        return BatchFeature(data=lowercase     ,				tensor_type=lowercase						)


