



'''simple docstring'''
import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
					    MODEL_MAPPING,
					    LevitForImageClassification,
					    LevitForImageClassificationWithTeacher,
					    LevitModel,
					)
					from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import LevitImageProcessor






class 							lowercase__	(							_a   ):





	def 	UpperCamelCase_  ( self					:				int ):







							'''simple docstring'''
							_UpperCamelCase					:		List[str] 				=   self.config_class(**self.inputs_dict )
							self.parent.assertTrue(hasattr(UpperCamelCase__ ,'hidden_sizes' ) )
							self.parent.assertTrue(hasattr(UpperCamelCase__ ,'num_attention_heads' ) )






class 							lowercase__	:





	def __init__( self					:				Optional[Any] ,lowerCamelCase__					:				Any ,lowerCamelCase__					:				Any=13 ,lowerCamelCase__					:				Dict=64 ,lowerCamelCase__					:				Optional[int]=3 ,lowerCamelCase__					:				List[Any]=3 ,lowerCamelCase__					:				str=2 ,lowerCamelCase__					:				Dict=1 ,lowerCamelCase__					:				Dict=16 ,lowerCamelCase__					:				Tuple=[128, 256, 384] ,lowerCamelCase__					:				Optional[Any]=[4, 6, 8] ,lowerCamelCase__					:				Dict=[2, 3, 4] ,lowerCamelCase__					:				List[Any]=[16, 16, 16] ,lowerCamelCase__					:				Optional[int]=0 ,lowerCamelCase__					:				int=[2, 2, 2] ,lowerCamelCase__					:				Any=[2, 2, 2] ,lowerCamelCase__					:				List[str]=0.0_2 ,lowerCamelCase__					:				Any=True ,lowerCamelCase__					:				List[Any]=True ,lowerCamelCase__					:				Optional[Any]=2 ,):







							'''simple docstring'''
							_UpperCamelCase					:		Optional[int] 				=   parent
							_UpperCamelCase					:		Union[str, Any] 				=   batch_size
							_UpperCamelCase					:		Tuple 				=   image_size
							_UpperCamelCase					:		Dict 				=   num_channels
							_UpperCamelCase					:		List[Any] 				=   kernel_size
							_UpperCamelCase					:		Dict 				=   stride
							_UpperCamelCase					:		Optional[int] 				=   padding
							_UpperCamelCase					:		Any 				=   hidden_sizes
							_UpperCamelCase					:		Union[str, Any] 				=   num_attention_heads
							_UpperCamelCase					:		Any 				=   depths
							_UpperCamelCase					:		Tuple 				=   key_dim
							_UpperCamelCase					:		Tuple 				=   drop_path_rate
							_UpperCamelCase					:		List[Any] 				=   patch_size
							_UpperCamelCase					:		str 				=   attention_ratio
							_UpperCamelCase					:		Dict 				=   mlp_ratio
							_UpperCamelCase					:		Optional[Any] 				=   initializer_range
							_UpperCamelCase					:		Optional[Any] 				=   [
							    ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
							    ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
							]
							_UpperCamelCase					:		Any 				=   is_training
							_UpperCamelCase					:		str 				=   use_labels
							_UpperCamelCase					:		Optional[int] 				=   num_labels
							_UpperCamelCase					:		List[Any] 				=   initializer_range





	def 	UpperCamelCase_  ( self					:				List[Any] ):







							'''simple docstring'''
							_UpperCamelCase					:		Any 				=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

							_UpperCamelCase					:		List[Any] 				=   None
							if self.use_labels:
													_UpperCamelCase					:		Dict 				=   ids_tensor([self.batch_size] ,self.num_labels )

							_UpperCamelCase					:		int 				=   self.get_config()
							return config, pixel_values, labels





	def 	UpperCamelCase_  ( self					:				Union[str, Any] ):







							'''simple docstring'''
							return LevitConfig(
							    image_size=self.image_size ,num_channels=self.num_channels ,kernel_size=self.kernel_size ,stride=self.stride ,padding=self.padding ,patch_size=self.patch_size ,hidden_sizes=self.hidden_sizes ,num_attention_heads=self.num_attention_heads ,depths=self.depths ,key_dim=self.key_dim ,drop_path_rate=self.drop_path_rate ,mlp_ratio=self.mlp_ratio ,attention_ratio=self.attention_ratio ,initializer_range=self.initializer_range ,down_ops=self.down_ops ,)





	def 	UpperCamelCase_  ( self					:				Any ,lowerCamelCase__					:				Optional[Any] ,lowerCamelCase__					:				str ,lowerCamelCase__					:				Optional[Any] ):







							'''simple docstring'''
							_UpperCamelCase					:		Optional[int] 				=   LevitModel(config=UpperCamelCase__ )
							model.to(UpperCamelCase__ )
							model.eval()
							_UpperCamelCase					:		List[Any] 				=   model(UpperCamelCase__ )
							_UpperCamelCase					:		Tuple 				=   (self.image_size, self.image_size)
							_UpperCamelCase				,			_UpperCamelCase					:		str 				=   image_size[0], image_size[1]
							for _ in range(4 ):
													_UpperCamelCase					:		Optional[int] 				=   floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 )
													_UpperCamelCase					:		Tuple 				=   floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 )
							self.parent.assertEqual(
							    result.last_hidden_state.shape ,(self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) ,)





	def 	UpperCamelCase_  ( self					:				List[Any] ,lowerCamelCase__					:				Optional[Any] ,lowerCamelCase__					:				Tuple ,lowerCamelCase__					:				List[Any] ):







							'''simple docstring'''
							_UpperCamelCase					:		Optional[int] 				=   self.num_labels
							_UpperCamelCase					:		List[str] 				=   LevitForImageClassification(UpperCamelCase__ )
							model.to(UpperCamelCase__ )
							model.eval()
							_UpperCamelCase					:		int 				=   model(UpperCamelCase__ ,labels=UpperCamelCase__ )
							self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) )





	def 	UpperCamelCase_  ( self					:				str ):







							'''simple docstring'''
							_UpperCamelCase					:		str 				=   self.prepare_config_and_inputs()
							_UpperCamelCase				,			_UpperCamelCase				,			_UpperCamelCase					:		List[str] 				=   config_and_inputs
							_UpperCamelCase					:		int 				=   {'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class 							lowercase__	(							_a						,					_a						,					unittest.TestCase   ):
	lowercase__  				=			(
	    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
	    if is_torch_available()
	    else ()
	)
	lowercase__  				=			(
	    {
	        """feature-extraction""": LevitModel,
	        """image-classification""": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
	    }
	    if is_torch_available()
	    else {}
	)

	lowercase__  				=			False
	lowercase__  				=			False
	lowercase__  				=			False
	lowercase__  				=			False
	lowercase__  				=			False





	def 	UpperCamelCase_  ( self					:				List[str] ):







							'''simple docstring'''
							_UpperCamelCase					:		Any 				=   LevitModelTester(self )
							_UpperCamelCase					:		Any 				=   ConfigTester(self ,config_class=UpperCamelCase__ ,has_text_modality=UpperCamelCase__ ,hidden_size=37 )





	def 	UpperCamelCase_  ( self					:				Optional[Any] ):







							'''simple docstring'''
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()





	def 	UpperCamelCase_  ( self					:				Any ):







							'''simple docstring'''
							return





	@unittest.skip(reason='Levit does not use inputs_embeds' )
	def 	UpperCamelCase_  ( self					:				Union[str, Any] ):







							'''simple docstring'''
							pass





	@unittest.skip(reason='Levit does not support input and output embeddings' )
	def 	UpperCamelCase_  ( self					:				Tuple ):







							'''simple docstring'''
							pass





	@unittest.skip(reason='Levit does not output attentions' )
	def 	UpperCamelCase_  ( self					:				Optional[Any] ):







							'''simple docstring'''
							pass





	def 	UpperCamelCase_  ( self					:				Any ):







							'''simple docstring'''
							_UpperCamelCase				,			_UpperCamelCase					:		Any 				=   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase					:		Optional[Any] 				=   model_class(UpperCamelCase__ )
													_UpperCamelCase					:		List[Any] 				=   inspect.signature(model.forward )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													_UpperCamelCase					:		Dict 				=   [*signature.parameters.keys()]

													_UpperCamelCase					:		List[str] 				=   ['pixel_values']
													self.assertListEqual(arg_names[:1] ,UpperCamelCase__ )





	def 	UpperCamelCase_  ( self					:				Dict ):







							'''simple docstring'''







							def check_hidden_states_output(lowerCamelCase__					:				Union[str, Any] ,lowerCamelCase__					:				List[str] ,lowerCamelCase__					:				List[Any] ):
													_UpperCamelCase					:		Any 				=   model_class(UpperCamelCase__ )
													model.to(UpperCamelCase__ )
													model.eval()

													with torch.no_grad():
																			_UpperCamelCase					:		str 				=   model(**self._prepare_for_class(UpperCamelCase__ ,UpperCamelCase__ ) )

													_UpperCamelCase					:		List[str] 				=   outputs.hidden_states

													_UpperCamelCase					:		int 				=   len(self.model_tester.depths ) + 1
													self.assertEqual(len(UpperCamelCase__ ) ,UpperCamelCase__ )

													_UpperCamelCase					:		int 				=   (self.model_tester.image_size, self.model_tester.image_size)
													_UpperCamelCase				,			_UpperCamelCase					:		Tuple 				=   image_size[0], image_size[1]
													for _ in range(4 ):
																			_UpperCamelCase					:		List[str] 				=   floor(
																			    (
																			        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
																			        / self.model_tester.stride
																			    )
																			    + 1 )
																			_UpperCamelCase					:		int 				=   floor(
																			    (
																			        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
																			        / self.model_tester.stride
																			    )
																			    + 1 )
													# verify the first hidden states (first block)
													self.assertListEqual(
													    list(hidden_states[0].shape[-2:] ) ,[
													        height * width,
													        self.model_tester.hidden_sizes[0],
													    ] ,)

							_UpperCamelCase				,			_UpperCamelCase					:		List[str] 				=   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase					:		Tuple 				=   True
													check_hidden_states_output(UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													_UpperCamelCase					:		str 				=   True

													check_hidden_states_output(UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ )





	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
	def 	UpperCamelCase_  ( self					:				Dict ):







							'''simple docstring'''
							pass





	def 	UpperCamelCase_  ( self					:				List[Any] ,lowerCamelCase__					:				Any ,lowerCamelCase__					:				Union[str, Any] ,lowerCamelCase__					:				int=False ):







							'''simple docstring'''
							_UpperCamelCase					:		Dict 				=   super()._prepare_for_class(UpperCamelCase__ ,UpperCamelCase__ ,return_labels=UpperCamelCase__ )

							if return_labels:
													if model_class.__name__ == "LevitForImageClassificationWithTeacher":
																			del inputs_dict["labels"]

							return inputs_dict





	def 	UpperCamelCase_  ( self					:				Optional[Any] ):







							'''simple docstring'''
							_UpperCamelCase					:		str 				=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCamelCase__ )





	def 	UpperCamelCase_  ( self					:				Dict ):







							'''simple docstring'''
							_UpperCamelCase					:		Optional[Any] 				=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ )





	def 	UpperCamelCase_  ( self					:				int ):







							'''simple docstring'''







							if not self.model_tester.is_training:
													return

							_UpperCamelCase				,			_UpperCamelCase					:		Optional[Any] 				=   self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase					:		List[Any] 				=   True

							for model_class in self.all_model_classes:
													# LevitForImageClassificationWithTeacher supports inference-only
													if (
													    model_class in get_values(UpperCamelCase__ )
													    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
													):
																			continue
													_UpperCamelCase					:		Union[str, Any] 				=   model_class(UpperCamelCase__ )
													model.to(UpperCamelCase__ )
													model.train()
													_UpperCamelCase					:		Dict 				=   self._prepare_for_class(UpperCamelCase__ ,UpperCamelCase__ ,return_labels=UpperCamelCase__ )
													_UpperCamelCase					:		List[str] 				=   model(**UpperCamelCase__ ).loss
													loss.backward()





	def 	UpperCamelCase_  ( self					:				int ):







							'''simple docstring'''
							_UpperCamelCase				,			_UpperCamelCase					:		str 				=   self.model_tester.prepare_config_and_inputs_for_common()
							if not self.model_tester.is_training:
													return

							_UpperCamelCase					:		List[str] 				=   False
							_UpperCamelCase					:		Optional[int] 				=   True

							for model_class in self.all_model_classes:
													if model_class in get_values(UpperCamelCase__ ) or not model_class.supports_gradient_checkpointing:
																			continue
													# LevitForImageClassificationWithTeacher supports inference-only
													if model_class.__name__ == "LevitForImageClassificationWithTeacher":
																			continue
													_UpperCamelCase					:		str 				=   model_class(UpperCamelCase__ )
													model.gradient_checkpointing_enable()
													model.to(UpperCamelCase__ )
													model.train()
													_UpperCamelCase					:		List[str] 				=   self._prepare_for_class(UpperCamelCase__ ,UpperCamelCase__ ,return_labels=UpperCamelCase__ )
													_UpperCamelCase					:		Dict 				=   model(**UpperCamelCase__ ).loss
													loss.backward()





	def 	UpperCamelCase_  ( self					:				int ):







							'''simple docstring'''
							_UpperCamelCase				,			_UpperCamelCase					:		str 				=   self.model_tester.prepare_config_and_inputs_for_common()

							_UpperCamelCase					:		Any 				=   [
							    {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float},
							    {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long},
							    {'title': 'regression', 'num_labels': 1, 'dtype': torch.float},
							]

							for model_class in self.all_model_classes:
													if (
													    model_class
													    not in [
													        *get_values(UpperCamelCase__ ),
													    ]
													    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
													):
																			continue

													for problem_type in problem_types:
																			with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}' ):
																									_UpperCamelCase					:		Any 				=   problem_type['title']
																									_UpperCamelCase					:		Any 				=   problem_type['num_labels']

																									_UpperCamelCase					:		List[Any] 				=   model_class(UpperCamelCase__ )
																									model.to(UpperCamelCase__ )
																									model.train()

																									_UpperCamelCase					:		Union[str, Any] 				=   self._prepare_for_class(UpperCamelCase__ ,UpperCamelCase__ ,return_labels=UpperCamelCase__ )

																									if problem_type["num_labels"] > 1:
																															_UpperCamelCase					:		Optional[int] 				=   inputs['labels'].unsqueeze(1 ).repeat(1 ,problem_type['num_labels'] )

																									_UpperCamelCase					:		Optional[Any] 				=   inputs['labels'].to(problem_type['dtype'] )

																									# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																									# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																									# they have the same size." which is a symptom something in wrong for the regression problem.
																									# See https://github.com/huggingface/transformers/issues/11780
																									with warnings.catch_warnings(record=UpperCamelCase__ ) as warning_list:
																															_UpperCamelCase					:		Any 				=   model(**UpperCamelCase__ ).loss
																									for w in warning_list:
																															if "Using a target size that is different to the input size" in str(w.message ):
																																					raise ValueError(
																																					    F'Something is going wrong in the regression problem: intercepted {w.message}' )

																									loss.backward()





	@slow
	def 	UpperCamelCase_  ( self					:				str ):







							'''simple docstring'''







							for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase					:		Tuple 				=   LevitModel.from_pretrained(UpperCamelCase__ )
													self.assertIsNotNone(UpperCamelCase__ )






def A__    (     ):
						_UpperCamelCase					:		Any 				=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						return image






@require_torch
@require_vision
class 							lowercase__	(							unittest.TestCase   ):





	@cached_property
	def 	UpperCamelCase_  ( self					:				Dict ):







							'''simple docstring'''
							return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )





	@slow
	def 	UpperCamelCase_  ( self					:				Any ):







							'''simple docstring'''
							_UpperCamelCase					:		Union[str, Any] 				=   LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(
							    UpperCamelCase__ )

							_UpperCamelCase					:		Any 				=   self.default_image_processor
							_UpperCamelCase					:		Optional[int] 				=   prepare_img()
							_UpperCamelCase					:		Optional[Any] 				=   image_processor(images=UpperCamelCase__ ,return_tensors='pt' ).to(UpperCamelCase__ )

							# forward pass
							with torch.no_grad():
													_UpperCamelCase					:		Tuple 				=   model(**UpperCamelCase__ )

							# verify the logits
							_UpperCamelCase					:		Optional[Any] 				=   torch.Size((1, 1000) )
							self.assertEqual(outputs.logits.shape ,UpperCamelCase__ )

							_UpperCamelCase					:		Dict 				=   torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7] ).to(UpperCamelCase__ )

							self.assertTrue(torch.allclose(outputs.logits[0, :3] ,UpperCamelCase__ ,atol=1E-4 ) )







'''simple docstring'''


from io import BytesIO
from typing import List, Union

import requests

from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_decord_available():
   import numpy as np
   from decord import VideoReader


if is_torch_available():
   from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING

_lowerCamelCase	:       Any      	=	logging.get_logger(__name__)

@add_end_docstrings(_a		)
class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    def __init__(  self      :					Any  ,						*UpperCamelCase__      :					Dict  ,						**UpperCamelCase__      :					Union[str, Any] ):


       """simple docstring"""







       super().__init__(*UpperCamelCase__  ,						**UpperCamelCase__ )
       requires_backends(self  ,						'decord' )
       self.check_model_type(UpperCamelCase__ )






    def  A       (  self      :					Optional[int]  ,						UpperCamelCase__      :					Optional[int]=None  ,						UpperCamelCase__      :					Optional[Any]=None  ,						UpperCamelCase__      :					Optional[Any]=None ):


       """simple docstring"""







       UpperCamelCase					=  {}
       if frame_sampling_rate is not None:
          UpperCamelCase					=  frame_sampling_rate
       if num_frames is not None:
          UpperCamelCase					=  num_frames

       UpperCamelCase					=  {}
       if top_k is not None:
          UpperCamelCase					=  top_k
       return preprocess_params, {}, postprocess_params






    def __call__(  self      :					List[str]  ,						UpperCamelCase__      :					Union[str, List[str]]  ,						**UpperCamelCase__      :					Dict ):


       """simple docstring"""







       return super().__call__(UpperCamelCase__  ,						**UpperCamelCase__ )






    def  A       (  self      :					Tuple  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Tuple=None  ,						UpperCamelCase__      :					Tuple=1 ):


       """simple docstring"""







       if num_frames is None:
          UpperCamelCase					=  self.model.config.num_frames

       if video.startswith('http://' ) or video.startswith('https://' ):
          UpperCamelCase					=  BytesIO(requests.get(UpperCamelCase__ ).content )

       UpperCamelCase					=  VideoReader(UpperCamelCase__ )
       videoreader.seek(0 )

       UpperCamelCase					=  0
       UpperCamelCase					=  num_frames * frame_sampling_rate - 1
       UpperCamelCase					=  np.linspace(UpperCamelCase__  ,						UpperCamelCase__  ,						num=UpperCamelCase__  ,						dtype=np.intaa )

       UpperCamelCase					=  videoreader.get_batch(UpperCamelCase__ ).asnumpy()
       UpperCamelCase					=  list(UpperCamelCase__ )

       UpperCamelCase					=  self.image_processor(UpperCamelCase__  ,						return_tensors=self.framework )
       return model_inputs






    def  A       (  self      :					Union[str, Any]  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  self.model(**UpperCamelCase__ )
       return model_outputs






    def  A       (  self      :					int  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					List[Any]=5 ):


       """simple docstring"""







       if top_k > self.model.config.num_labels:
          UpperCamelCase					=  self.model.config.num_labels

       if self.framework == "pt":
          UpperCamelCase					=  model_outputs.logits.softmax(-1 )[0]
          UpperCamelCase				,      UpperCamelCase					=  probs.topk(UpperCamelCase__ )
       else:
          raise ValueError(f"""Unsupported framework: {self.framework}""" )

       UpperCamelCase					=  scores.tolist()
       UpperCamelCase					=  ids.tolist()
       return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase__  ,						UpperCamelCase__ )]

