




import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase						,lowercase						,lowercase						,lowercase=True						,lowercase="pt"     )  ->   List[str]:
   snake_case      :				Dict				=       {"""add_prefix_space""": True} if isinstance(__UpperCamelCase						,__UpperCamelCase     ) and not line.startswith(""" """     ) else {}
   snake_case      :				Any				=       padding_side
   return tokenizer(
       [line]						,max_length=__UpperCamelCase						,padding="""max_length""" if pad_to_max_length else None						,truncation=__UpperCamelCase						,return_tensors=__UpperCamelCase						,add_special_tokens=__UpperCamelCase						,**__UpperCamelCase						,)




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase						,lowercase=None						,)  ->   Union[str, Any]:
   snake_case      :				int				=       input_ids.ne(__UpperCamelCase     ).any(dim=0     )
   if attention_mask is None:
      return input_ids[:, keep_column_mask]
   else:
      return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])




class 						__lowercase		(SCREAMING_SNAKE_CASE__							):




      """simple docstring"""





      def __init__(      self				,      A				,      A				,      A				,      A				,      A="train"				,      A=None				,      A=None				,      A=None				,      A=""				,      )		->				Union[str, Any]:
         super().__init__()
         snake_case      :				int				=       Path(A	).joinpath(type_path + """.source"""	)
         snake_case      :				List[Any]				=       Path(A	).joinpath(type_path + """.target"""	)
         snake_case      :				List[Any]				=       self.get_char_lens(self.src_file	)
         snake_case      :				Tuple				=       max_source_length
         snake_case      :				Any				=       max_target_length
         assert min(self.src_lens	) > 0, f"""found empty line in {self.src_file}"""
         snake_case      :				Tuple				=       tokenizer
         snake_case      :				str				=       prefix
         if n_obs is not None:
            snake_case      :				Any				=       self.src_lens[:n_obs]
         snake_case      :				List[Any]				=       src_lang
         snake_case      :				Any				=       tgt_lang

      def __len__(      self	)		->				Any:
         return len(self.src_lens	)

      def __getitem__(      self				,      A	)		->				Dict[str, torch.Tensor]:
         snake_case      :				List[str]				=       index + 1  # linecache starts at 1
         snake_case      :				List[str]				=       self.prefix + linecache.getline(str(self.src_file	)				,      A	).rstrip("""\n"""	)
         snake_case      :				Optional[Any]				=       linecache.getline(str(self.tgt_file	)				,      A	).rstrip("""\n"""	)
         assert source_line, f"""empty source line for index {index}"""
         assert tgt_line, f"""empty tgt line for index {index}"""

         # Need to add eos token manually for T5
         if isinstance(self.tokenizer				,      A	):
            source_line += self.tokenizer.eos_token
            tgt_line += self.tokenizer.eos_token

         # Pad source and target to the right
         snake_case      :				int				=       (
             self.tokenizer.question_encoder if isinstance(self.tokenizer				,      A	) else self.tokenizer
         )
         snake_case      :				Union[str, Any]				=       self.tokenizer.generator if isinstance(self.tokenizer				,      A	) else self.tokenizer

         snake_case      :				Any				=       encode_line(A				,      A				,      self.max_source_length				,      """right"""	)
         snake_case      :				List[str]				=       encode_line(A				,      A				,      self.max_target_length				,      """right"""	)

         snake_case      :				Any				=       source_inputs["""input_ids"""].squeeze()
         snake_case      :				Dict				=       target_inputs["""input_ids"""].squeeze()
         snake_case      :				int				=       source_inputs["""attention_mask"""].squeeze()
         return {
             "input_ids": source_ids,
             "attention_mask": src_mask,
             "decoder_input_ids": target_ids,
         }

      @staticmethod
      def 	UpperCAmelCase      (      A	)		->				Optional[int]:
         return [len(A	) for x in Path(A	).open().readlines()]

      def 	UpperCAmelCase      (      self				,      A	)		->				Dict[str, torch.Tensor]:
         snake_case      :				List[str]				=       torch.stack([x["""input_ids"""] for x in batch]	)
         snake_case      :				List[str]				=       torch.stack([x["""attention_mask"""] for x in batch]	)
         snake_case      :				str				=       torch.stack([x["""decoder_input_ids"""] for x in batch]	)
         snake_case      :				Dict				=       (
             self.tokenizer.generator.pad_token_id
             if isinstance(self.tokenizer				,      A	)
             else self.tokenizer.pad_token_id
         )
         snake_case      :				Optional[Any]				=       (
             self.tokenizer.question_encoder.pad_token_id
             if isinstance(self.tokenizer				,      A	)
             else self.tokenizer.pad_token_id
         )
         snake_case      :				Any				=       trim_batch(A				,      A	)
         snake_case	,					snake_case      :				Dict				=       trim_batch(A				,      A				,      attention_mask=A	)
         snake_case      :				List[Any]				=       {
             """input_ids""": source_ids,
             """attention_mask""": source_mask,
             """decoder_input_ids""": y,
         }
         return batch




lowerCamelCase       :       List[str]        =    getLogger(__name__)




def 						SCREAMING_SNAKE_CASE__					(    lowercase     )  ->   int:
   return list(itertools.chain.from_iterable(__UpperCamelCase     )     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase     )  ->   Dict:
   snake_case      :				Optional[int]				=       get_git_info()
   save_json(__UpperCamelCase						,os.path.join(__UpperCamelCase						,"""git_log.json"""     )     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase						,lowercase=4						,**lowercase     )  ->   Optional[int]:
   with open(__UpperCamelCase						,"""w"""     ) as f:
      json.dump(__UpperCamelCase						,__UpperCamelCase						,indent=__UpperCamelCase						,**__UpperCamelCase     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase     )  ->   Any:
   with open(__UpperCamelCase     ) as f:
      return json.load(__UpperCamelCase     )




def 						SCREAMING_SNAKE_CASE__					(    )  ->   List[Any]:
   snake_case      :				Optional[Any]				=       git.Repo(search_parent_directories=__UpperCamelCase     )
   snake_case      :				Union[str, Any]				=       {
       """repo_id""": str(__UpperCamelCase     ),
       """repo_sha""": str(repo.head.object.hexsha     ),
       """repo_branch""": str(repo.active_branch     ),
       """hostname""": str(socket.gethostname()     ),
   }
   return repo_infos




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase     )  ->   Tuple:
   return list(map(__UpperCamelCase						,__UpperCamelCase     )     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase     )  ->   List[str]:
   with open(__UpperCamelCase						,"""wb"""     ) as f:
      return pickle.dump(__UpperCamelCase						,__UpperCamelCase     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase     )  ->   Dict:

   def remove_articles(lowercase     ):
      return re.sub(R"""\b(a|an|the)\b"""						,""" """						,__UpperCamelCase     )

   def white_space_fix(lowercase     ):
      return " ".join(text.split()     )

   def remove_punc(lowercase     ):
      snake_case      :				Union[str, Any]				=       set(string.punctuation     )
      return "".join(ch for ch in text if ch not in exclude     )

   def lower(lowercase     ):
      return text.lower()

   return white_space_fix(remove_articles(remove_punc(lower(__UpperCamelCase     )     )     )     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase     )  ->   int:
   snake_case      :				Dict				=       normalize_answer(__UpperCamelCase     ).split()
   snake_case      :				List[str]				=       normalize_answer(__UpperCamelCase     ).split()
   snake_case      :				List[str]				=       Counter(__UpperCamelCase     ) & Counter(__UpperCamelCase     )
   snake_case      :				List[str]				=       sum(common.values()     )
   if num_same == 0:
      return 0
   snake_case      :				List[Any]				=       1.0 * num_same / len(__UpperCamelCase     )
   snake_case      :				Optional[Any]				=       1.0 * num_same / len(__UpperCamelCase     )
   snake_case      :				int				=       (2 * precision * recall) / (precision + recall)
   return fa




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase     )  ->   int:
   return normalize_answer(__UpperCamelCase     ) == normalize_answer(__UpperCamelCase     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase     )  ->   Optional[Any]:
   assert len(__UpperCamelCase     ) == len(__UpperCamelCase     )
   snake_case      :				List[str]				=       0
   for hypo, pred in zip(__UpperCamelCase						,__UpperCamelCase     ):
      em += exact_match_score(__UpperCamelCase						,__UpperCamelCase     )
   if len(__UpperCamelCase     ) > 0:
      em /= len(__UpperCamelCase     )
   return {"em": em}




def 						SCREAMING_SNAKE_CASE__					(    lowercase     )  ->   List[Any]:
   return model_prefix.startswith("""rag"""     )




def 						SCREAMING_SNAKE_CASE__					(    lowercase						,lowercase						,lowercase     )  ->   Dict:
   snake_case      :				Optional[int]				=       {p: p for p in extra_params}
   # T5 models don't have `dropout` param, they have `dropout_rate` instead
   snake_case      :				Optional[Any]				=       """dropout_rate"""
   for p in extra_params:
      if getattr(__UpperCamelCase						,__UpperCamelCase						,__UpperCamelCase     ):
         if not hasattr(__UpperCamelCase						,__UpperCamelCase     ) and not hasattr(__UpperCamelCase						,equivalent_param[p]     ):
            logger.info("""config doesn't have a `{}` attribute""".format(__UpperCamelCase     )     )
            delattr(__UpperCamelCase						,__UpperCamelCase     )
            continue
         snake_case      :				Tuple				=       p if hasattr(__UpperCamelCase						,__UpperCamelCase     ) else equivalent_param[p]
         setattr(__UpperCamelCase						,__UpperCamelCase						,getattr(__UpperCamelCase						,__UpperCamelCase     )     )
         delattr(__UpperCamelCase						,__UpperCamelCase     )
   return hparams, config






import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel
      from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
          AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      )


if is_torchaudio_available():
      import torchaudio

      from transformers import ASTFeatureExtractor


class      lowerCamelCase    :
  """simple docstring"""







  def __init__(							self       :				List[Any]     ,   __magic_name__       :				Any     ,   __magic_name__       :				List[Any]=13     ,   __magic_name__       :				List[Any]=2     ,   __magic_name__       :				Tuple=24     ,   __magic_name__       :				List[str]=16     ,   __magic_name__       :				Dict=True     ,   __magic_name__       :				List[Any]=True     ,   __magic_name__       :				Optional[int]=32     ,   __magic_name__       :				Tuple=5     ,   __magic_name__       :				int=4     ,   __magic_name__       :				Tuple=37     ,   __magic_name__       :				List[str]="gelu"     ,   __magic_name__       :				Tuple=0.1     ,   __magic_name__       :				Tuple=0.1     ,   __magic_name__       :				Union[str, Any]=10     ,   __magic_name__       :				Tuple=0.02     ,   __magic_name__       :				Tuple=None     ,   __magic_name__       :				Any=2     ,   __magic_name__       :				Dict=2     ,   )     ->		int:
        SCREAMING_SNAKE_CASE_      =     parent
        SCREAMING_SNAKE_CASE_      =     batch_size
        SCREAMING_SNAKE_CASE_      =     patch_size
        SCREAMING_SNAKE_CASE_      =     max_length
        SCREAMING_SNAKE_CASE_      =     num_mel_bins
        SCREAMING_SNAKE_CASE_      =     is_training
        SCREAMING_SNAKE_CASE_      =     use_labels
        SCREAMING_SNAKE_CASE_      =     hidden_size
        SCREAMING_SNAKE_CASE_      =     num_hidden_layers
        SCREAMING_SNAKE_CASE_      =     num_attention_heads
        SCREAMING_SNAKE_CASE_      =     intermediate_size
        SCREAMING_SNAKE_CASE_      =     hidden_act
        SCREAMING_SNAKE_CASE_      =     hidden_dropout_prob
        SCREAMING_SNAKE_CASE_      =     attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE_      =     type_sequence_label_size
        SCREAMING_SNAKE_CASE_      =     initializer_range
        SCREAMING_SNAKE_CASE_      =     scope
        SCREAMING_SNAKE_CASE_      =     frequency_stride
        SCREAMING_SNAKE_CASE_      =     time_stride

        # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
        SCREAMING_SNAKE_CASE_      =     (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
        SCREAMING_SNAKE_CASE_      =     (self.max_length - self.patch_size) // self.time_stride + 1
        SCREAMING_SNAKE_CASE_      =     frequency_out_dimension * time_out_dimension
        SCREAMING_SNAKE_CASE_      =     num_patches + 2







  def       __A   (							self       :				Any      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

        SCREAMING_SNAKE_CASE_      =     None
        if self.use_labels:
              SCREAMING_SNAKE_CASE_      =     ids_tensor([self.batch_size]     ,   self.type_sequence_label_size      )

        SCREAMING_SNAKE_CASE_      =     self.get_config()

        return config, input_values, labels







  def       __A   (							self       :				Any      )     ->		Dict:
        return ASTConfig(
            patch_size=self.patch_size     ,   max_length=self.max_length     ,   num_mel_bins=self.num_mel_bins     ,   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     ,   is_decoder=__magic_name__     ,   initializer_range=self.initializer_range     ,   frequency_stride=self.frequency_stride     ,   time_stride=self.time_stride     ,   )







  def       __A   (							self       :				List[Any]     ,   __magic_name__       :				List[str]     ,   __magic_name__       :				str     ,   __magic_name__       :				List[str]      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     ASTModel(config=__magic_name__      )
        model.to(__magic_name__      )
        model.eval()
        SCREAMING_SNAKE_CASE_      =     model(__magic_name__      )
        self.parent.assertEqual(result.last_hidden_state.shape     ,   (self.batch_size, self.seq_length, self.hidden_size)      )







  def       __A   (							self       :				Tuple      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     self.prepare_config_and_inputs()
        (
            (
            SCREAMING_SNAKE_CASE_
        )   ,       (
            SCREAMING_SNAKE_CASE_
        )   ,       (
            SCREAMING_SNAKE_CASE_
        )   ,       
        )      =     config_and_inputs
        SCREAMING_SNAKE_CASE_      =     {"input_values": input_values}
        return config, inputs_dict



@require_torch
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







  lowerCamelCase__   =  (
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  lowerCamelCase__   =  (
      {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
      if is_torch_available()
      else {}
  )
  lowerCamelCase__   =  False
  lowerCamelCase__   =  False
  lowerCamelCase__   =  False
  lowerCamelCase__   =  False







  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				Dict     ,   __magic_name__       :				Optional[int]     ,   __magic_name__       :				Tuple      )     ->		Tuple:
        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

        return False







  def       __A   (							self       :				Optional[Any]      )     ->		Optional[Any]:
        SCREAMING_SNAKE_CASE_      =     ASTModelTester(self      )
        SCREAMING_SNAKE_CASE_      =     ConfigTester(self     ,   config_class=__magic_name__     ,   has_text_modality=__magic_name__     ,   hidden_size=37      )







  def       __A   (							self       :				Union[str, Any]      )     ->		Dict:
        self.config_tester.run_common_tests()







  @unittest.skip(reason="AST does not use inputs_embeds"      )
  def       __A   (							self       :				Optional[Any]      )     ->		Tuple:
        pass







  def       __A   (							self       :				int      )     ->		int:
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs_for_common()

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







  def       __A   (							self       :				List[Any]      )     ->		str:
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_      =     ["input_values"]
              self.assertListEqual(arg_names[:1]     ,   __magic_name__      )







  def       __A   (							self       :				int      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__magic_name__      )







  @slow
  def       __A   (							self       :				int      )     ->		int:
        for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_      =     ASTModel.from_pretrained(__magic_name__      )
              self.assertIsNotNone(__magic_name__      )



def    a__       (						):
      SCREAMING_SNAKE_CASE_      =     hf_hub_download(
          repo_id="nielsr/audio-spectogram-transformer-checkpoint"   ,					filename="sample_audio.flac"   ,					repo_type="dataset" )

      SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     torchaudio.load(__UpperCamelCase )

      return audio, sampling_rate





@require_torch
@require_torchaudio
class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @cached_property
  def       __A   (							self       :				List[Any]      )     ->		List[Any]:
        return (
            ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      )
            if is_torchaudio_available()
            else None
        )







  @slow
  def       __A   (							self       :				Union[str, Any]      )     ->		Optional[int]:
        SCREAMING_SNAKE_CASE_      =     self.default_feature_extractor
        SCREAMING_SNAKE_CASE_      =     ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      ).to(__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     self.default_feature_extractor
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     prepare_audio()
        SCREAMING_SNAKE_CASE_      =     audio.squeeze().numpy()
        SCREAMING_SNAKE_CASE_      =     feature_extractor(__magic_name__     ,   sampling_rate=__magic_name__     ,   return_tensors="pt"      ).to(__magic_name__      )

        # forward pass
        with torch.no_grad():
              SCREAMING_SNAKE_CASE_      =     model(**__magic_name__      )

        # verify the logits
        SCREAMING_SNAKE_CASE_      =     torch.Size((1, 527)      )
        self.assertEqual(outputs.logits.shape     ,   __magic_name__      )

        SCREAMING_SNAKE_CASE_      =     torch.tensor([-0.8760, -7.0042, -8.6602]      ).to(__magic_name__      )

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


