



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 		_lowercase		:

   def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[Any]=13							,   __lowerCAmelCase			:       Optional[Any]=7							,   __lowerCAmelCase			:       Any=True							,   __lowerCAmelCase			:       List[str]=True							,   __lowerCAmelCase			:       Union[str, Any]=True							,   __lowerCAmelCase			:       Dict=True							,   __lowerCAmelCase			:       Any=99							,   __lowerCAmelCase			:       Optional[Any]=24							,   __lowerCAmelCase			:       Any=2							,   __lowerCAmelCase			:       Dict=6							,   __lowerCAmelCase			:       int=37							,   __lowerCAmelCase			:       Any="gelu"							,   __lowerCAmelCase			:       int=0.1							,   __lowerCAmelCase			:       Optional[int]=0.1							,   __lowerCAmelCase			:       Optional[Any]=512							,   __lowerCAmelCase			:       Any=16							,   __lowerCAmelCase			:       Optional[Any]=2							,   __lowerCAmelCase			:       Optional[int]=0.0_2							,   __lowerCAmelCase			:       List[str]=3							,   __lowerCAmelCase			:       Optional[Any]=None							,   __lowerCAmelCase			:       str=1000							,   )       ->				List[str]:


    """simple docstring"""






    a						=		parent
    a						=		batch_size
    a						=		seq_length
    a						=		is_training
    a						=		use_input_mask
    a						=		use_token_type_ids
    a						=		use_labels
    a						=		vocab_size
    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						=		max_position_embeddings
    a						=		type_vocab_size
    a						=		type_sequence_label_size
    a						=		initializer_range
    a						=		num_labels
    a						=		scope
    a						=		range_bbox

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


    """simple docstring"""






    a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size							)

    a						=		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]:
       a						=		bbox[i, j, 3]
       a						=		bbox[i, j, 1]
       a						=		t
      if bbox[i, j, 2] < bbox[i, j, 0]:
       a						=		bbox[i, j, 2]
       a						=		bbox[i, j, 0]
       a						=		t

    a						=		None
    if self.use_input_mask:
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   vocab_size=2							)

    a						=		None
    if self.use_token_type_ids:
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.type_vocab_size							)

    a						=		None
    a						=		None
    if self.use_labels:
     a						=		ids_tensor([self.batch_size]							,   self.type_sequence_label_size							)
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.num_labels							)

    a						=		self.get_config()

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

   def 		A							(      self			:       Tuple							)       ->				List[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 		A							(      self			:       Dict							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       int							,   )       ->				Optional[Any]:


    """simple docstring"""






    a						=		LiltModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   bbox=__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   bbox=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   bbox=__lowerCAmelCase							)

    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 		A							(      self			:       str							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   )       ->				Optional[int]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		LiltForTokenClassification(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   bbox=__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.num_labels)							)

   def 		A							(      self			:       int							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[int]							,   )       ->				Optional[int]:


    """simple docstring"""






    a						=		LiltForQuestionAnswering(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   bbox=__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   start_positions=__lowerCAmelCase							,   end_positions=__lowerCAmelCase							,   )
    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 		A							(      self			:       Any							)       ->				Any:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    (
        (
        a  
    )		,  (
        a  
    )		,  (
        a  
    )		,  (
        a  
    )		,  (
        a  
    )		,  (
        a  
    )		,  (
        a  
    )		,    
    )						=		config_and_inputs
    a						=		{
        "input_ids": input_ids,
        "bbox": bbox,
        "token_type_ids": token_type_ids,
        "attention_mask": input_mask,
    }
    return config, inputs_dict



@require_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   UpperCAmelCase__,   unittest.TestCase	):
   _UpperCAmelCase     	=			(
       (
           LiltModel,
           LiltForSequenceClassification,
           LiltForTokenClassification,
           LiltForQuestionAnswering,
       )
       if is_torch_available()
       else ()
   )
   _UpperCAmelCase     	=			(
       {
           '''feature-extraction''': LiltModel,
           '''question-answering''': LiltForQuestionAnswering,
           '''text-classification''': LiltForSequenceClassification,
           '''token-classification''': LiltForTokenClassification,
           '''zero-shot''': LiltForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False

   def 		A							(      self			:       int							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       int							)       ->				int:


    """simple docstring"""






    return True

   def 		A							(      self			:       int							)       ->				int:


    """simple docstring"""






    a						=		LiltModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       str							)       ->				int:


    """simple docstring"""






    self.config_tester.run_common_tests()

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


    """simple docstring"""






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

   def 		A							(      self			:       List[Any]							)       ->				Any:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
     a						=		type
     self.model_tester.create_and_check_model(*__lowerCAmelCase							)

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase							)

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase							)




   @slow
   def 		A							(      self			:       Union[str, Any]							)       ->				Optional[int]:


    """simple docstring"""






    for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     a						=		LiltModel.from_pretrained(__lowerCAmelCase							)
     self.assertIsNotNone(__lowerCAmelCase							)



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

   def 		A							(      self			:       int							)       ->				int:


    """simple docstring"""






    a						=		LiltModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base"							).to(__lowerCAmelCase							)

    a						=		torch.tensor([[1, 2]]							,   device=__lowerCAmelCase							)
    a						=		torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]]							,   device=__lowerCAmelCase							)

    # forward pass
    with torch.no_grad():
     a						=		model(input_ids=__lowerCAmelCase							,   bbox=__lowerCAmelCase							)

    a						=		torch.Size([1, 2, 768]							)
    a						=		torch.tensor(
        [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]]							,   device=__lowerCAmelCase							,   )

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









from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


A_		:     List[str]        =     logging.get_logger(__name__)



class 		_lowercase		(       UpperCAmelCase__	):
   _UpperCAmelCase     	=			['''audio_values''', '''audio_mask''']

   def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       Dict=2048							,   __lowerCAmelCase			:       List[Any]=1							,   __lowerCAmelCase			:       Dict=[16, 16]							,   __lowerCAmelCase			:       str=128							,   __lowerCAmelCase			:       Optional[int]=4_4100							,   __lowerCAmelCase			:       int=86							,   __lowerCAmelCase			:       Optional[Any]=2048							,   __lowerCAmelCase			:       str=0.0							,   **__lowerCAmelCase			:       Optional[int]							,   )       ->				Union[str, Any]:


    """simple docstring"""






    super().__init__(
        feature_size=__lowerCAmelCase							,   sampling_rate=__lowerCAmelCase							,   padding_value=__lowerCAmelCase							,   **__lowerCAmelCase							,   )

    a						=		spectrogram_length
    a						=		num_channels
    a						=		patch_size
    a						=		feature_size // self.patch_size[1]
    a						=		n_fft
    a						=		sampling_rate // hop_length_to_sampling_rate
    a						=		sampling_rate
    a						=		padding_value
    a						=		mel_filter_bank(
        num_frequency_bins=1 + n_fft // 2							,   num_mel_filters=__lowerCAmelCase							,   min_frequency=0.0							,   max_frequency=2_2_0_5_0.0							,   sampling_rate=__lowerCAmelCase							,   norm="slaney"							,   mel_scale="slaney"							,   ).T

   def 		A							(      self			:       List[str]							,   __lowerCAmelCase			:       np.array							)       ->				np.ndarray:


    """simple docstring"""






    a						=		spectrogram(
        __lowerCAmelCase							,   window_function(self.n_fft							,   "hann"							)							,   frame_length=self.n_fft							,   hop_length=self.hop_length							,   power=2.0							,   mel_filters=self.mel_filters.T							,   log_mel="dB"							,   db_range=8_0.0							,   )
    a						=		log_spec[:, :-1]
    a						=		log_spec - 2_0.0
    a						=		np.clip(log_spec / 4_0.0							,   -2.0							,   0.0							) + 1.0
    return log_spec




   def __call__(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,   __lowerCAmelCase			:       Optional[Union[str, TensorType]] = None							,   __lowerCAmelCase			:       Optional[bool] = True							,   __lowerCAmelCase			:       Optional[int] = None							,   __lowerCAmelCase			:       bool = False							,   __lowerCAmelCase			:       bool = False							,   **__lowerCAmelCase			:       Optional[int]							,   )       ->				BatchFeature:


    """simple docstring"""






    if sampling_rate is not None:
     if sampling_rate != self.sampling_rate:
      raise ValueError(
          "This feature extractor is set to support sampling rate"
          f""" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"""
          f""" with {self.sampling_rate} and not {sampling_rate}."""							)
    else:
     logger.warning(
         "It is strongly recommended to pass the `sampling_rate` argument to this function. "
         "Failing to do so can result in silent errors that might be hard to debug."							)

    a						=		isinstance(__lowerCAmelCase							,   np.ndarray							) and len(raw_speech.shape							) > 1
    if is_batched_numpy and len(raw_speech.shape							) > 2:
     raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""							)
    a						=		is_batched_numpy or (
        isinstance(__lowerCAmelCase							,   (list, tuple)							) and (isinstance(raw_speech[0]							,   (np.ndarray, tuple, list)							))
    )
    if is_batched:
     a						=		[np.asarray([speech]							,   dtype=np.floataa							).T for speech in raw_speech]
    elif not is_batched and not isinstance(__lowerCAmelCase							,   np.ndarray							):
     a						=		np.asarray(__lowerCAmelCase							,   dtype=np.floataa							)
    elif isinstance(__lowerCAmelCase							,   np.ndarray							) and raw_speech.dtype is np.dtype(np.floataa							):
     a						=		raw_speech.astype(np.floataa							)
    # always return batch
    if not is_batched:
     a						=		[np.asarray([raw_speech]							).T]

    # Convert audio signals to log mel spectrograms, truncate by time axis
    a						=		[
        self._np_extract_fbank_features(waveform.squeeze()							).T[: self.spectrogram_length] for waveform in raw_speech
    ]
    if isinstance(audio_features[0]							,   __lowerCAmelCase							):
     a						=		[np.asarray(__lowerCAmelCase							,   dtype=np.floataa							) for feature in audio_features]

    # Create audio attention mask
    a						=		max(
        [ceil(feature.shape[0] / self.patch_size[0]							) * self.freq_len for feature in audio_features]							)  # The maximum number of audio patches in a batch
    if return_attention_mask:
     a						=		[
         (ceil(feature.shape[0] / self.patch_size[0]							) * self.freq_len) * [1]
         + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]							) * self.freq_len) * [0]
         for feature in audio_features
     ]
     a						=		np.array(__lowerCAmelCase							).astype(np.floataa							)

    # convert into correct format for padding
    a						=		max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
    a						=		np.ones([len(__lowerCAmelCase							), 1, max_time_len, self.feature_size]							).astype(np.floataa							)
    a						=		padded_audio_features * self.padding_value
    for i in range(len(__lowerCAmelCase							)							):
     a						=		audio_features[i]
     a						=		feature

    # return as BatchFeature
    if return_attention_mask:
     a						=		{"audio_values": padded_audio_features, "audio_mask": audio_mask}
    else:
     a						=		{"audio_values": padded_audio_features}

    a						=		BatchFeature(data=__lowerCAmelCase							,   tensor_type=__lowerCAmelCase							)
    return encoded_inputs

