






import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

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

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 torch import nn

	from transformers import (
	    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
	    TimesformerForVideoClassification,
	    TimesformerModel,
	)
	from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from transformers import VideoMAEImageProcessor



class 							SCREAMING_SNAKE_CASE__		:





					"""simple docstring"""






					def __init__(      self  :						List[Any]							,	__A  :						Tuple							,	__A  :						Optional[int]=1_3							,	__A  :						Tuple=1_0							,	__A  :						List[Any]=3							,	__A  :						Tuple=2							,	__A  :						List[str]=2							,	__A  :						Tuple=True							,	__A  :						Optional[Any]=True							,	__A  :						Optional[Any]=3_2							,	__A  :						Optional[Any]=5							,	__A  :						Any=4							,	__A  :						Any=3_7							,	__A  :						Optional[int]="gelu"							,	__A  :						List[str]=0.1							,	__A  :						int=0.1							,	__A  :						Dict=1_0							,	__A  :						str=0.0_2							,	__A  :						str="divided_space_time"							,	__A  :						List[Any]=None							,	):
						snake_case__				:   List[str]     =						parent
						snake_case__				:   str     =						batch_size
						snake_case__				:   Optional[Any]     =						image_size
						snake_case__				:   Dict     =						num_channels
						snake_case__				:   List[str]     =						patch_size
						snake_case__				:   int     =						num_frames
						snake_case__				:   List[str]     =						is_training
						snake_case__				:   Union[str, Any]     =						use_labels
						snake_case__				:   int     =						hidden_size
						snake_case__				:   List[Any]     =						num_hidden_layers
						snake_case__				:   str     =						num_attention_heads
						snake_case__				:   int     =						intermediate_size
						snake_case__				:   Tuple     =						hidden_act
						snake_case__				:   List[str]     =						hidden_dropout_prob
						snake_case__				:   int     =						attention_probs_dropout_prob
						snake_case__				:   List[str]     =						attention_type
						snake_case__				:   int     =						initializer_range
						snake_case__				:   List[str]     =						scope
						snake_case__				:   Any     =						num_labels

						# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
						snake_case__				:   List[Any]     =						(image_size // patch_size) ** 2
						snake_case__				:   str     =						(num_frames) * self.num_patches_per_frame + 1



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   Optional[int]     =						floats_tensor(
						    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] )

						snake_case__				:   Any     =						None
						if self.use_labels:
							snake_case__				:   str     =						ids_tensor([self.batch_size]							,	self.num_labels )

						snake_case__				:   Optional[Any]     =						self.get_config()

						return config, pixel_values, labels



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   Tuple     =						TimesformerConfig(
						    image_size=self.image_size							,	patch_size=self.patch_size							,	num_channels=self.num_channels							,	num_frames=self.num_frames							,	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							,	initializer_range=self.initializer_range							,	attention_type=self.attention_type							,	)
						snake_case__				:   List[Any]     =						self.num_labels
						return config



					def  _lowercase  (      self  :						Dict							,	__A  :						Tuple							,	__A  :						str							,	__A  :						Union[str, Any] ):
						snake_case__				:   Any     =						TimesformerModel(config=__A )
						model.to(__A )
						model.eval()
						snake_case__				:   int     =						model(__A )
						self.parent.assertEqual(result.last_hidden_state.shape							,	(self.batch_size, self.seq_length, self.hidden_size) )



					def  _lowercase  (      self  :						Dict							,	__A  :						List[Any]							,	__A  :						Tuple							,	__A  :						str ):
						snake_case__				:   Any     =						TimesformerForVideoClassification(__A )
						model.to(__A )
						model.eval()

						snake_case__				:   Dict     =						model(__A )

						# verify the logits shape
						snake_case__				:   Union[str, Any]     =						torch.Size((self.batch_size, self.num_labels) )
						self.parent.assertEqual(result.logits.shape							,	__A )






					def  _lowercase  (      self  :						Tuple ):
						snake_case__				:   Dict     =						self.prepare_config_and_inputs()
						snake_case__				:   List[str]     =						config_and_inputs
						snake_case__				:   Tuple     =						{"pixel_values": pixel_values}
						return config, inputs_dict



@require_torch
class 							SCREAMING_SNAKE_CASE__		(       UpperCamelCase_				,     UpperCamelCase_				,     unittest.TestCase		):





					"""simple docstring"""






					a_			=	(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
					a_			=	(
					    {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification}
					    if is_torch_available()
					    else {}
					)

					a_			=	False
					a_			=	False
					a_			=	False
					a_			=	False



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   Optional[int]     =						TimesformerModelTester(self )
						snake_case__				:   Tuple     =						ConfigTester(
						    self							,	config_class=__A							,	has_text_modality=__A							,	hidden_size=3_7 )



					def  _lowercase  (      self  :						Dict							,	__A  :						Tuple							,	__A  :						Dict							,	__A  :						Union[str, Any]=False ):
						snake_case__				:   Optional[Any]     =						copy.deepcopy(__A )

						if return_labels:
							if model_class in get_values(__A ):
								snake_case__				:   List[str]     =						torch.zeros(
								    self.model_tester.batch_size							,	dtype=torch.long							,	device=__A )

						return inputs_dict



					def  _lowercase  (      self  :						List[str] ):
						self.config_tester.run_common_tests()



					@unittest.skip(reason="TimeSformer does not use inputs_embeds" )
					def  _lowercase  (      self  :						Union[str, Any] ):
						pass



					def  _lowercase  (      self  :						Dict ):
						snake_case__				:   Union[str, Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   Any     =						model_class(__A )
							self.assertIsInstance(model.get_input_embeddings()							,	(nn.Module) )
							snake_case__				:   Tuple     =						model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(__A							,	nn.Linear ) )



					def  _lowercase  (      self  :						Optional[Any] ):
						snake_case__				:   str     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   Any     =						model_class(__A )
							snake_case__				:   Tuple     =						inspect.signature(model.forward )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							snake_case__				:   Union[str, Any]     =						[*signature.parameters.keys()]

							snake_case__				:   int     =						["pixel_values"]
							self.assertListEqual(arg_names[:1]							,	__A )



					def  _lowercase  (      self  :						str ):
						snake_case__				:   Optional[Any]     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__A )



					def  _lowercase  (      self  :						Optional[Any] ):
						snake_case__				:   str     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_video_classification(*__A )



					@slow
					def  _lowercase  (      self  :						Union[str, Any] ):
						for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__				:   List[str]     =						TimesformerModel.from_pretrained(__A )
							self.assertIsNotNone(__A )



					def  _lowercase  (      self  :						Tuple ):
						if not self.has_attentions:
							pass

						else:
							snake_case__				:   int     =						self.model_tester.prepare_config_and_inputs_for_common()
							snake_case__				:   Union[str, Any]     =						True

							for model_class in self.all_model_classes:
								snake_case__				:   List[Any]     =						self.model_tester.seq_length
								snake_case__				:   Optional[int]     =						self.model_tester.num_frames

								snake_case__				:   int     =						True
								snake_case__				:   Optional[Any]     =						False
								snake_case__				:   Optional[int]     =						True
								snake_case__				:   Optional[int]     =						model_class(__A )
								model.to(__A )
								model.eval()
								with torch.no_grad():
									snake_case__				:   str     =						model(**self._prepare_for_class(__A							,	__A ) )
								snake_case__				:   Dict     =						outputs.attentions
								self.assertEqual(len(__A )							,	self.model_tester.num_hidden_layers )

								# check that output_attentions also work using config
								del inputs_dict["output_attentions"]
								snake_case__				:   List[Any]     =						True
								snake_case__				:   List[str]     =						model_class(__A )
								model.to(__A )
								model.eval()
								with torch.no_grad():
									snake_case__				:   int     =						model(**self._prepare_for_class(__A							,	__A ) )
								snake_case__				:   Dict     =						outputs.attentions
								self.assertEqual(len(__A )							,	self.model_tester.num_hidden_layers )

								# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
								self.assertListEqual(
								    list(attentions[0].shape[-3:] )							,	[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]							,	)
								snake_case__				:   Dict     =						len(__A )

								# Check attention is always last and order is fine
								snake_case__				:   Union[str, Any]     =						True
								snake_case__				:   List[str]     =						True
								snake_case__				:   Optional[Any]     =						model_class(__A )
								model.to(__A )
								model.eval()
								with torch.no_grad():
									snake_case__				:   str     =						model(**self._prepare_for_class(__A							,	__A ) )

								self.assertEqual(out_len + 1							,	len(__A ) )

								snake_case__				:   str     =						outputs.attentions

								self.assertEqual(len(__A )							,	self.model_tester.num_hidden_layers )

								# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
								self.assertListEqual(
								    list(self_attentions[0].shape[-3:] )							,	[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]							,	)






					def  _lowercase  (      self  :						Optional[int] ):
						def check_hidden_states_output(__A  :						str							,	__A  :						Dict							,	__A  :						Optional[Any] ):
							snake_case__				:   Optional[int]     =						model_class(__A )
							model.to(__A )
							model.eval()

							with torch.no_grad():
								snake_case__				:   str     =						model(**self._prepare_for_class(__A							,	__A ) )

							snake_case__				:   Dict     =						outputs.hidden_states
							snake_case__				:   Union[str, Any]     =						self.model_tester.num_hidden_layers + 1
							self.assertEqual(len(__A )							,	__A )

							snake_case__				:   Tuple     =						self.model_tester.seq_length

							self.assertListEqual(
							    list(hidden_states[0].shape[-2:] )							,	[seq_length, self.model_tester.hidden_size]							,	)

						snake_case__				:   int     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   int     =						True
							check_hidden_states_output(__A							,	__A							,	__A )

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

							check_hidden_states_output(__A							,	__A							,	__A )







def   SCREAMING_SNAKE_CASE       (				):
	snake_case__				:   List[Any]     =						hf_hub_download(
	    repo_id="hf-internal-testing/spaghetti-video"  ,						filename="eating_spaghetti.npy"  ,						repo_type="dataset"							)
	snake_case__				:   List[Any]     =						np.load(snake_case_							)
	return list(snake_case_							)





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





					"""simple docstring"""






					@cached_property
					def  _lowercase  (      self  :						int ):
						# logits were tested with a different mean and std, so we use the same here
						return (
						    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]							,	image_std=[0.5, 0.5, 0.5] )
						    if is_vision_available()
						    else None
						)






					@slow
					def  _lowercase  (      self  :						Optional[int] ):
						snake_case__				:   Tuple     =						TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to(
						    __A )

						snake_case__				:   Tuple     =						self.default_image_processor
						snake_case__				:   str     =						prepare_video()
						snake_case__				:   str     =						image_processor(video[:8]							,	return_tensors="pt" ).to(__A )

						# forward pass
						with torch.no_grad():
							snake_case__				:   Optional[Any]     =						model(**__A )

						# verify the logits
						snake_case__				:   Optional[Any]     =						torch.Size((1, 4_0_0) )
						self.assertEqual(outputs.logits.shape							,	__A )

						snake_case__				:   Tuple     =						torch.tensor([-0.3_0_1_6, -0.7_7_1_3, -0.4_2_0_5] ).to(__A )

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











# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position

__lowerCamelCase      :    Union[str, Any]   		=   """2.13.1"""

import platform

import pyarrow
from packaging import version


if version.parse(platform.python_version()) < version.parse("""3.7"""):
	raise ImportWarning(
	    """To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition."""
	)

if version.parse(pyarrow.__version__).major < 8:
	raise ImportWarning(
	    """To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n"""
	    """If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`."""
	)

del platform
del pyarrow
del version

from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
    list_datasets,
    list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
    NamedSplit,
    NamedSplitAll,
    Split,
    SplitBase,
    SplitDict,
    SplitGenerator,
    SplitInfo,
    SubSplitInfo,
    percent,
)
from .tasks import *
from .utils import *
from .utils import logging


# deprecated modules
from datasets import arrow_dataset as _arrow_dataset  # isort:skip
from datasets import utils as _utils  # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager  # isort:skip

__lowerCamelCase      :    List[Any]   		=   concatenate_datasets
__lowerCamelCase      :    List[str]   		=   DownloadConfig
__lowerCamelCase      :    Union[str, Any]   		=   DownloadManager
__lowerCamelCase      :    str   		=   DownloadMode
__lowerCamelCase      :    Union[str, Any]   		=   DownloadConfig
__lowerCamelCase      :    List[str]   		=   DownloadMode
__lowerCamelCase      :    Dict   		=   DownloadManager

del _arrow_dataset, _utils, _deprecated_download_manager



