




'''simple docstring'''







import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
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


if is_torch_available():
    import torch
    from torch import nn

    from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
    from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from transformers import VivitImageProcessor

class   _snake_case:






 def __init__(self					:     Optional[Any]						,		a					:     Tuple						,		a					:     Dict=2						,		a					:     Tuple=True						,		a					:     List[str]=True						,		a					:     Dict=10						,		a					:     Optional[Any]=10						,		a					:     Dict=8						,		a					:     Union[str, Any]=[2, 4, 4]						,		a					:     List[str]=3						,		a					:     Optional[int]=7_68						,		a					:     str=5						,		a					:     Optional[Any]=4						,		a					:     str=37						,		a					:     List[Any]="gelu_fast"						,		a					:     Any=0.0						,		a					:     int=0.0						,		a					:     Optional[int]=0.02						,		a					:     List[Any]=1e-06						,		a					:     Tuple=True						,		a					:     Optional[Any]=None						,		)					->      Union[str, Any]:






    """simple docstring"""


    A__         =    parent
    A__         =    batch_size
    A__         =    is_training
    A__         =    use_labels
    A__         =    num_labels
    A__         =    image_size
    A__         =    num_frames
    A__         =    tubelet_size
    A__         =    num_channels
    A__         =    hidden_size
    A__         =    num_hidden_layers
    A__         =    num_attention_heads
    A__         =    intermediate_size
    A__         =    hidden_act
    A__         =    hidden_dropout_prob
    A__         =    attention_probs_dropout_prob
    A__         =    initializer_range
    A__         =    layer_norm_eps
    A__         =    qkv_bias
    A__         =    scope

    A__         =    (
        (self.image_size // self.tubelet_size[2])
        * (self.image_size // self.tubelet_size[1])
        * (self.num_frames // self.tubelet_size[0])
    ) + 1  # CLS token






 def 	_UpperCamelCase   (self					:     Any						)					->      Union[str, Any]:






    """simple docstring"""


    A__         =    floats_tensor(
        [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]						)

    A__         =    None
    if self.use_labels:
       A__         =    ids_tensor([self.batch_size]						,		self.num_labels						)

    A__         =    self.get_config()

    return config, pixel_values, labels






 def 	_UpperCamelCase   (self					:     Tuple						)					->      int:






    """simple docstring"""


    A__         =    VivitConfig(
        num_frames=self.num_frames						,		image_size=self.image_size						,		tubelet_size=self.tubelet_size						,		num_channels=self.num_channels						,		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						,		layer_norm_eps=self.layer_norm_eps						,		qkv_bias=self.qkv_bias						,		)
    A__         =    self.num_labels
    return config






 def 	_UpperCamelCase   (self					:     Any						,		a					:     int						,		a					:     Optional[Any]						,		a					:     List[Any]						)					->      Union[str, Any]:






    """simple docstring"""


    A__         =    VivitModel(config=a						)
    model.to(a						)
    model.eval()
    A__         =    model(a						)
    self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, self.seq_length, self.hidden_size)						)






 def 	_UpperCamelCase   (self					:     List[str]						,		a					:     Tuple						,		a					:     Dict						,		a					:     Dict						)					->      Optional[int]:






    """simple docstring"""


    A__         =    VivitForVideoClassification(a						)
    model.to(a						)
    model.eval()

    A__         =    model(a						)

    # verify the logits shape
    A__         =    torch.Size((self.batch_size, self.num_labels)						)
    self.parent.assertEqual(result.logits.shape						,		a						)






 def 	_UpperCamelCase   (self					:     List[str]						)					->      Optional[int]:






    """simple docstring"""


    A__         =    self.prepare_config_and_inputs()
    A__     , A__     , A__         =    config_and_inputs
    A__         =    {'pixel_values': pixel_values}
    return config, inputs_dict




@require_torch
class   _snake_case( UpperCAmelCase					,   unittest.TestCase			):
 __snake_case:       Union[str, Any]									=				(VivitModel, VivitForVideoClassification) if is_torch_available() else ()

 __snake_case:       str									=				False
 __snake_case:       int									=				False
 __snake_case:       Optional[int]									=				False
 __snake_case:       Dict									=				False






 def 	_UpperCamelCase   (self					:     Union[str, Any]						)					->      List[str]:






    """simple docstring"""


    A__         =    VivitModelTester(self						)
    A__         =    ConfigTester(self						,		config_class=a						,		has_text_modality=a						,		hidden_size=37						)






 def 	_UpperCamelCase   (self					:     Union[str, Any]						,		a					:     Tuple						,		a					:     Union[str, Any]						,		a					:     int=False						)					->      List[Any]:






    """simple docstring"""


    A__         =    copy.deepcopy(a						)

    if return_labels:
       if model_class in get_values(a						):
          A__         =    torch.zeros(
              self.model_tester.batch_size						,		dtype=torch.long						,		device=a						)

    return inputs_dict






 def 	_UpperCamelCase   (self					:     Dict						)					->      Dict:






    """simple docstring"""


    self.config_tester.run_common_tests()






 @unittest.skip(reason='Vivit does not use inputs_embeds'						)
 def 	_UpperCamelCase   (self					:     Tuple						)					->      Tuple:






    """simple docstring"""


    pass






 def 	_UpperCamelCase   (self					:     Union[str, Any]						)					->      int:






    """simple docstring"""


    A__     , A__         =    self.model_tester.prepare_config_and_inputs_for_common()

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






 def 	_UpperCamelCase   (self					:     Tuple						)					->      List[Any]:






    """simple docstring"""


    A__     , A__         =    self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       A__         =    model_class(a						)
       A__         =    inspect.signature(model.forward						)
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       A__         =    [*signature.parameters.keys()]

       A__         =    ['pixel_values', 'head_mask']
       self.assertListEqual(arg_names[:2]						,		a						)






 def 	_UpperCamelCase   (self					:     str						)					->      Union[str, Any]:






    """simple docstring"""


    A__         =    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*a						)






 def 	_UpperCamelCase   (self					:     int						)					->      Any:






    """simple docstring"""


    A__         =    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_video_classification(*a						)






 @slow
 def 	_UpperCamelCase   (self					:     int						)					->      str:






    """simple docstring"""


    for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       A__         =    VivitModel.from_pretrained(a						)
       self.assertIsNotNone(a						)






 def 	_UpperCamelCase   (self					:     Optional[Any]						)					->      int:






    """simple docstring"""


    A__     , A__         =    self.model_tester.prepare_config_and_inputs_for_common()
    A__         =    True

    for model_class in self.all_model_classes:
       A__         =    self.model_tester.seq_length

       A__         =    True
       A__         =    False
       A__         =    True
       A__         =    model_class(a						)
       model.to(a						)
       model.eval()
       with torch.no_grad():
          A__         =    model(**self._prepare_for_class(a						,		a						)						)
       A__         =    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"]
       A__         =    True
       A__         =    model_class(a						)
       model.to(a						)
       model.eval()
       with torch.no_grad():
          A__         =    model(**self._prepare_for_class(a						,		a						)						)
       A__         =    outputs.attentions
       self.assertEqual(len(a						)						,		self.model_tester.num_hidden_layers						)

       self.assertListEqual(
           list(attentions[0].shape[-3:]						)						,		[self.model_tester.num_attention_heads, seq_len, seq_len]						,		)
       A__         =    len(a						)

       # Check attention is always last and order is fine
       A__         =    True
       A__         =    True
       A__         =    model_class(a						)
       model.to(a						)
       model.eval()
       with torch.no_grad():
          A__         =    model(**self._prepare_for_class(a						,		a						)						)

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

       A__         =    outputs.attentions

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

       self.assertListEqual(
           list(self_attentions[0].shape[-3:]						)						,		[self.model_tester.num_attention_heads, seq_len, seq_len]						,		)






 def 	_UpperCamelCase   (self					:     List[str]						)					->      Any:






    """simple docstring"""


    def check_hidden_states_output(a					:     Dict						,		a					:     Optional[int]						,		a					:     Any						):
       A__         =    model_class(a						)
       model.to(a						)
       model.eval()

       with torch.no_grad():
          A__         =    model(**self._prepare_for_class(a						,		a						)						)

       A__         =    outputs.hidden_states
       A__         =    self.model_tester.num_hidden_layers + 1
       self.assertEqual(len(a						)						,		a						)

       A__         =    self.model_tester.seq_length

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

    A__     , A__         =    self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       A__         =    True
       check_hidden_states_output(a						,		a						,		a						)

       # check that output_hidden_states also work using config
       del inputs_dict["output_hidden_states"]
       A__         =    True

       check_hidden_states_output(a						,		a						,		a						)






 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'						)
 def 	_UpperCamelCase   (self					:     List[str]						)					->      Optional[int]:






    """simple docstring"""


    pass







def 	_A			(   ):






   '''simple docstring'''







   A__         =    hf_hub_download(
       repo_id='hf-internal-testing/spaghetti-video'			,filename='eating_spaghetti_32_frames.npy'			,repo_type='dataset'	)
   A__         =    np.load(UpperCAmelCase	)
   return list(UpperCAmelCase	)







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






 @cached_property
 def 	_UpperCamelCase   (self					:     str						)					->      Optional[Any]:






    """simple docstring"""


    return VivitImageProcessor() if is_vision_available() else None






 @slow
 def 	_UpperCamelCase   (self					:     List[Any]						)					->      Optional[int]:






    """simple docstring"""


    A__         =    VivitForVideoClassification.from_pretrained('google/vivit-b-16x2-kinetics400'						).to(a						)

    A__         =    self.default_image_processor
    A__         =    prepare_video()
    A__         =    image_processor(a						,		return_tensors='pt'						).to(a						)

    # forward pass
    with torch.no_grad():
       A__         =    model(**a						)

    # verify the logits
    A__         =    torch.Size((1, 4_00)						)
    self.assertEqual(outputs.logits.shape						,		a						)

    # taken from original model
    A__         =    torch.tensor([-1.0543, 2.0764, -0.2104, 0.4439, -0.9658]						).to(a						)

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






'''simple docstring'''







from dataclasses import dataclass

lowerCAmelCase_    	=							'''0.1'''
lowerCAmelCase_    	=							'''Lucia Harcekova'''

@dataclass
class   _snake_case:
 __snake_case:       int
 __snake_case:       int
 __snake_case:       str






 def __repr__(self					:     Optional[int]						)					->      str:






    """simple docstring"""


    return f"""({self.offset}, {self.length}, {self.indicator})"""




class   _snake_case:






 def __init__(self					:     Optional[Any]						,		a					:     int = 13						,		a					:     int = 6						)					->      None:






    """simple docstring"""


    A__         =    window_size
    A__         =    lookahead_buffer_size
    A__         =    self.window_size - self.lookahead_buffer_size






 def 	_UpperCamelCase   (self					:     Optional[Any]						,		a					:     str						)					->      list[Token]:






    """simple docstring"""


    A__         =    []
    A__         =    ''

    # while there are still characters in text to compress
    while text:
       # find the next encoding phrase
       # - triplet with offset, length, indicator (the next encoding character)
       A__         =    self._find_encoding_token(a						,		a						)

       # update the search buffer:
       # - add new characters from text into it
       # - check if size exceed the max search buffer size, if so, drop the
       #   oldest elements
       search_buffer += text[: token.length + 1]
       if len(a						) > self.search_buffer_size:
          A__         =    search_buffer[-self.search_buffer_size :]

       # update the text
       A__         =    text[token.length + 1 :]

       # append the token to output
       output.append(a						)

    return output






 def 	_UpperCamelCase   (self					:     Optional[int]						,		a					:     list[Token]						)					->      str:






    """simple docstring"""


    A__         =    ''

    for token in tokens:
       for _ in range(token.length						):
          output += output[-token.offset]
       output += token.indicator

    return output






 def 	_UpperCamelCase   (self					:     Any						,		a					:     str						,		a					:     str						)					->      Token:






    """simple docstring"""


    if not text:
       raise ValueError('We need some text to work with.'						)

    # Initialise result parameters to default values
    A__     , A__         =    0, 0

    if not search_buffer:
       return Token(a						,		a						,		text[length]						)

    for i, character in enumerate(a						):
       A__         =    len(a						) - i
       if character == text[0]:
          A__         =    self._match_length_from_index(a						,		a						,		0						,		a						)
          # if the found length is bigger than the current or if it's equal,
          # which means it's offset is smaller: update offset and length
          if found_length >= length:
             A__     , A__         =    found_offset, found_length

    return Token(a						,		a						,		text[length]						)






 def 	_UpperCamelCase   (self					:     int						,		a					:     str						,		a					:     str						,		a					:     int						,		a					:     int						)					->      int:






    """simple docstring"""


    if not text or text[text_index] != window[window_index]:
       return 0
    return 1 + self._match_length_from_index(
        a						,		window + text[text_index]						,		text_index + 1						,		window_index + 1						)


if __name__ == "__main__":
    from doctest import testmod

    testmod()
    # Initialize compressor class
    lowerCAmelCase_    	=							LZaaCompressor(window_size=1_3, lookahead_buffer_size=6)

    # Example
    lowerCAmelCase_    	=							'''cabracadabrarrarrad'''
    lowerCAmelCase_    	=							lzaa_compressor.compress(TEXT)
    print(lzaa_compressor.compress('''ababcbababaa'''))
    lowerCAmelCase_    	=							lzaa_compressor.decompress(compressed_text)
    assert decompressed_text == TEXT, "The LZ77 algorithm returned the invalid result."


