

import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
			import jax.numpy as jnp

			from transformers.models.albert.modeling_flax_albert import (
			    FlaxAlbertForMaskedLM,
			    FlaxAlbertForMultipleChoice,
			    FlaxAlbertForPreTraining,
			    FlaxAlbertForQuestionAnswering,
			    FlaxAlbertForSequenceClassification,
			    FlaxAlbertForTokenClassification,
			    FlaxAlbertModel,
			)






class _UpperCamelCase							(							unittest.TestCase      ):
			'''simple docstring'''







			def __init__(	self							:       Union[str, Any]					,					a							:       str					,					a							:       Tuple=13					,					a							:       List[Any]=7					,					a							:       List[Any]=True					,					a							:       List[str]=True					,					a							:       str=True					,					a							:       List[str]=True					,					a							:       Union[str, Any]=99					,					a							:       int=32					,					a							:       Any=5					,					a							:       Any=4					,					a							:       Tuple=37					,					a							:       str="gelu"					,					a							:       Tuple=0.1					,					a							:       Tuple=0.1					,					a							:       List[str]=512					,					a							:       str=16					,					a							:       List[str]=2					,					a							:       Optional[int]=0.02					,					a							:       Optional[int]=4					,					)							->				List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					int    =				parent
				SCREAMING_SNAKE_CASE      :					Any    =				batch_size
				SCREAMING_SNAKE_CASE      :					Any    =				seq_length
				SCREAMING_SNAKE_CASE      :					int    =				is_training
				SCREAMING_SNAKE_CASE      :					int    =				use_attention_mask
				SCREAMING_SNAKE_CASE      :					Tuple    =				use_token_type_ids
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				use_labels
				SCREAMING_SNAKE_CASE      :					List[str]    =				vocab_size
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				hidden_size
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				num_hidden_layers
				SCREAMING_SNAKE_CASE      :					int    =				num_attention_heads
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				intermediate_size
				SCREAMING_SNAKE_CASE      :					int    =				hidden_act
				SCREAMING_SNAKE_CASE      :					List[Any]    =				hidden_dropout_prob
				SCREAMING_SNAKE_CASE      :					str    =				attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE      :					Any    =				max_position_embeddings
				SCREAMING_SNAKE_CASE      :					Any    =				type_vocab_size
				SCREAMING_SNAKE_CASE      :					Tuple    =				type_sequence_label_size
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				initializer_range
				SCREAMING_SNAKE_CASE      :					Tuple    =				num_choices
			def 							__UpperCamelCase       (	self							:       int		)							->				str:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Tuple    =				ids_tensor([self.batch_size, self.seq_length]					,					self.vocab_size		)

				SCREAMING_SNAKE_CASE      :					Any    =				None
				if self.use_attention_mask:
					SCREAMING_SNAKE_CASE      :					Any    =				random_attention_mask([self.batch_size, self.seq_length]		)

				SCREAMING_SNAKE_CASE      :					Dict    =				None
				if self.use_token_type_ids:
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				ids_tensor([self.batch_size, self.seq_length]					,					self.type_vocab_size		)

				SCREAMING_SNAKE_CASE      :					int    =				AlbertConfig(
				    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					,					is_decoder=__UpperCAmelCase					,					initializer_range=self.initializer_range					,					)

				return config, input_ids, token_type_ids, attention_mask






			def 							__UpperCamelCase       (	self							:       Any		)							->				str:

				"""simple docstring"""

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






@require_flax
class _UpperCamelCase							(							__A							,		unittest.TestCase      ):
			'''simple docstring'''







			lowerCamelCase__							=(
			    (
			        FlaxAlbertModel,
			        FlaxAlbertForPreTraining,
			        FlaxAlbertForMaskedLM,
			        FlaxAlbertForMultipleChoice,
			        FlaxAlbertForQuestionAnswering,
			        FlaxAlbertForSequenceClassification,
			        FlaxAlbertForTokenClassification,
			        FlaxAlbertForQuestionAnswering,
			    )
			    if is_flax_available()
			    else ()
			)
			def 							__UpperCamelCase       (	self							:       Union[str, Any]		)							->				str:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					List[str]    =				FlaxAlbertModelTester(self		)






			@slow
			def 							__UpperCamelCase       (	self							:       int		)							->				List[str]:

				"""simple docstring"""

				for model_class_name in self.all_model_classes:
					SCREAMING_SNAKE_CASE      :					Dict    =				model_class_name.from_pretrained("albert-base-v2"		)
					SCREAMING_SNAKE_CASE      :					int    =				model(np.ones((1, 1)		)		)
					self.assertIsNotNone(__UpperCAmelCase		)






@require_flax
class _UpperCamelCase							(							unittest.TestCase      ):
			'''simple docstring'''







			@slow
			def 							__UpperCamelCase       (	self							:       List[str]		)							->				Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				FlaxAlbertModel.from_pretrained("albert-base-v2"		)
				SCREAMING_SNAKE_CASE      :					str    =				np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]		)
				SCREAMING_SNAKE_CASE      :					Any    =				np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]		)
				SCREAMING_SNAKE_CASE      :					int    =				model(__UpperCAmelCase					,					attention_mask=__UpperCAmelCase		)[0]
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				(1, 11, 768)
				self.assertEqual(output.shape					,					__UpperCAmelCase		)
				SCREAMING_SNAKE_CASE      :					int    =				np.array(
				    [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]		)

				self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]					,					__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							 =     logging.get_logger(__name__)
@add_end_docstrings(__A       )
class 			UpperCamelCase__(	__A       ):





						def __init__(				self						,*__UpperCAmelCase						,**__UpperCAmelCase   )    -> Tuple:
													super().__init__(*__UpperCAmelCase						,**__UpperCAmelCase   )
													requires_backends(self						,'decord'   )
													self.check_model_type(__UpperCAmelCase   )





						def  snake_case__		(				self						,__UpperCAmelCase=None						,__UpperCAmelCase=None						,__UpperCAmelCase=None   )    -> int:
													A__		   =							{}
													if frame_sampling_rate is not None:
																				A__		   =							frame_sampling_rate
													if num_frames is not None:
																				A__		   =							num_frames

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





						def __call__(				self						,__UpperCAmelCase						,**__UpperCAmelCase   )    -> Dict:
													return super().__call__(__UpperCAmelCase						,**__UpperCAmelCase   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=None						,__UpperCAmelCase=1   )    -> Union[str, Any]:
													if num_frames is None:
																				A__		   =							self.model.config.num_frames

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

													A__		   =							VideoReader(__UpperCAmelCase   )
													videoreader.seek(0   )

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

													A__		   =							videoreader.get_batch(__UpperCAmelCase   ).asnumpy()
													A__		   =							list(__UpperCAmelCase   )

													A__		   =							self.image_processor(__UpperCAmelCase						,return_tensors=self.framework   )
													return model_inputs





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													A__		   =							self.model(**__UpperCAmelCase   )
													return model_outputs





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=5   )    -> Union[str, Any]:
													if top_k > self.model.config.num_labels:
																				A__		   =							self.model.config.num_labels

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

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





