






import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCamelCase	:							Optional[int]				=random.Random()

if is_torch_available():
 import torch







def 		SCREAMING_SNAKE_CASE							(					__lowerCAmelCase					,    __lowerCAmelCase=1.0					,    __lowerCAmelCase=None					,    __lowerCAmelCase=None			) ->	int:
     if rng is None:
          UpperCamelCase__			:   Optional[int]       				=  global_rng

     UpperCamelCase__			:   Optional[Any]       				=  []
     for batch_idx in range(shape[0]			):
          values.append([]			)
          for _ in range(shape[1]			):
               values[-1].append(rng.random() * scale			)

     return values





class 			__a  (    unittest.TestCase       ):







 def __init__(		self					:   Tuple							,   SCREAMING_SNAKE_CASE					:   int							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=7							,   SCREAMING_SNAKE_CASE					:   List[str]=4_00							,   SCREAMING_SNAKE_CASE					:   int=20_00							,   SCREAMING_SNAKE_CASE					:   List[str]=1							,   SCREAMING_SNAKE_CASE					:   int=0.0							,   SCREAMING_SNAKE_CASE					:   List[str]=1_60_00							,   SCREAMING_SNAKE_CASE					:   Any=True							,   SCREAMING_SNAKE_CASE					:   List[str]=True							,   ):


      '''simple docstring'''






      UpperCamelCase__			:   List[Any]       				=  parent
      UpperCamelCase__			:   Dict       				=  batch_size
      UpperCamelCase__			:   int       				=  min_seq_length
      UpperCamelCase__			:   List[Any]       				=  max_seq_length
      UpperCamelCase__			:   Any       				=  (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
      UpperCamelCase__			:   Optional[Any]       				=  feature_size
      UpperCamelCase__			:   Any       				=  padding_value
      UpperCamelCase__			:   List[str]       				=  sampling_rate
      UpperCamelCase__			:   Optional[Any]       				=  return_attention_mask
      UpperCamelCase__			:   Union[str, Any]       				=  do_normalize







 def 					__lowercase					(		self					:   Any						):


      '''simple docstring'''






      return {
          "feature_size": self.feature_size,
          "padding_value": self.padding_value,
          "sampling_rate": self.sampling_rate,
          "return_attention_mask": self.return_attention_mask,
          "do_normalize": self.do_normalize,
      }







 def 					__lowercase					(		self					:   Union[str, Any]							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=False							,   SCREAMING_SNAKE_CASE					:   str=False						):


      '''simple docstring'''






      def _flatten(SCREAMING_SNAKE_CASE					:   int						):
           return list(itertools.chain(*SCREAMING_SNAKE_CASE						)						)

      if equal_length:
           UpperCamelCase__			:   int       				=  floats_list((self.batch_size, self.max_seq_length)						)
      else:
           # make sure that inputs increase in size
           UpperCamelCase__			:   Any       				=  [
               _flatten(floats_list((x, self.feature_size)						)						)
               for x in range(self.min_seq_length							,   self.max_seq_length							,   self.seq_length_diff						)
           ]

      if numpify:
           UpperCamelCase__			:   Any       				=  [np.asarray(SCREAMING_SNAKE_CASE						) for x in speech_inputs]

      return speech_inputs







@require_torch
@require_torchaudio
class 			__a  (    A__       ,   unittest.TestCase       ):
 _lowerCAmelCase       :       Any        = ASTFeatureExtractor







 def 					__lowercase					(		self					:   Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   int       				=  ASTFeatureExtractionTester(self						)







 def 					__lowercase					(		self					:   str						):


      '''simple docstring'''






      UpperCamelCase__			:   Tuple       				=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
      # create three inputs of length 800, 1000, and 1200
      UpperCamelCase__			:   str       				=  [floats_list((1, x)						)[0] for x in range(8_00							,   14_00							,   2_00						)]
      UpperCamelCase__			:   str       				=  [np.asarray(SCREAMING_SNAKE_CASE						) for speech_input in speech_inputs]

      # Test not batched input
      UpperCamelCase__			:   Tuple       				=  feat_extract(speech_inputs[0]							,   return_tensors="np"						).input_values
      UpperCamelCase__			:   List[str]       				=  feat_extract(np_speech_inputs[0]							,   return_tensors="np"						).input_values
      self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   atol=1e-3						)						)

      # Test batched
      UpperCamelCase__			:   int       				=  feat_extract(SCREAMING_SNAKE_CASE							,   padding=SCREAMING_SNAKE_CASE							,   return_tensors="np"						).input_values
      UpperCamelCase__			:   Optional[int]       				=  feat_extract(SCREAMING_SNAKE_CASE							,   padding=SCREAMING_SNAKE_CASE							,   return_tensors="np"						).input_values
      for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						):
           self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   atol=1e-3						)						)

      # Test 2-D numpy arrays are batched.
      UpperCamelCase__			:   Dict       				=  [floats_list((1, x)						)[0] for x in (8_00, 8_00, 8_00)]
      UpperCamelCase__			:   Optional[int]       				=  np.asarray(SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   List[Any]       				=  feat_extract(SCREAMING_SNAKE_CASE							,   return_tensors="np"						).input_values
      UpperCamelCase__			:   int       				=  feat_extract(SCREAMING_SNAKE_CASE							,   return_tensors="np"						).input_values
      for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						):
           self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   atol=1e-3						)						)







 @require_torch
 def 					__lowercase					(		self					:   List[Any]						):


      '''simple docstring'''






      import torch

      UpperCamelCase__			:   Optional[int]       				=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
      UpperCamelCase__			:   List[str]       				=  np.random.rand(1_00						).astype(np.floataa						)
      UpperCamelCase__			:   Any       				=  np_speech_inputs.tolist()

      for inputs in [py_speech_inputs, np_speech_inputs]:
           UpperCamelCase__			:   int       				=  feature_extractor.pad([{"input_values": inputs}]							,   return_tensors="np"						)
           self.assertTrue(np_processed.input_values.dtype == np.floataa						)
           UpperCamelCase__			:   Union[str, Any]       				=  feature_extractor.pad([{"input_values": inputs}]							,   return_tensors="pt"						)
           self.assertTrue(pt_processed.input_values.dtype == torch.floataa						)







 def 					__lowercase					(		self					:   Optional[int]							,   SCREAMING_SNAKE_CASE					:   str						):


      '''simple docstring'''






      from datasets import load_dataset

      UpperCamelCase__			:   Union[str, Any]       				=  load_dataset("hf-internal-testing/librispeech_asr_dummy"							,   "clean"							,   split="validation"						)
      # automatic decoding with librispeech
      UpperCamelCase__			:   List[Any]       				=  ds.sort("id"						).select(range(SCREAMING_SNAKE_CASE						)						)[:num_samples]["audio"]

      return [x["array"] for x in speech_samples]







 @require_torch
 def 					__lowercase					(		self					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   List[str]       				=  torch.tensor(
          [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
           -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
           -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
           -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]						)
      # fmt: on

      UpperCamelCase__			:   str       				=  self._load_datasamples(1						)
      UpperCamelCase__			:   List[str]       				=  ASTFeatureExtractor()
      UpperCamelCase__			:   str       				=  feature_extractor(SCREAMING_SNAKE_CASE							,   return_tensors="pt"						).input_values
      self.assertEquals(input_values.shape							,   (1, 10_24, 1_28)						)
      self.assertTrue(torch.allclose(input_values[0, 0, :30]							,   SCREAMING_SNAKE_CASE							,   atol=1e-4						)						)







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool





class 			__a  (    A__       ):
 _lowerCAmelCase       :       str        = '''facebook/bart-large-mnli'''
 _lowerCAmelCase       :       Tuple        = (
     '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '''
     '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. '''
     '''It returns the most likely label in the list of provided `labels` for the input text.'''
 )
 _lowerCAmelCase       :       Any        = '''text_classifier'''
 _lowerCAmelCase       :       int        = AutoTokenizer
 _lowerCAmelCase       :       Union[str, Any]        = AutoModelForSequenceClassification

 _lowerCAmelCase       :       Union[str, Any]        = ['''text''', ['''text''']]
 _lowerCAmelCase       :       Dict        = ['''text''']







 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      super().setup()
      UpperCamelCase__			:   Dict       				=  self.model.config
      UpperCamelCase__			:   Union[str, Any]       				=  -1
      for idx, label in config.idalabel.items():
           if label.lower().startswith("entail"						):
                UpperCamelCase__			:   List[str]       				=  int(SCREAMING_SNAKE_CASE						)
      if self.entailment_id == -1:
           raise ValueError("Could not determine the entailment ID from the model config, please pass it at init."						)







 def 					__lowercase					(		self					:   Tuple							,   SCREAMING_SNAKE_CASE					:   Tuple							,   SCREAMING_SNAKE_CASE					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Any       				=  labels
      return self.pre_processor(
          [text] * len(SCREAMING_SNAKE_CASE						)							,   [F'This example is {label}' for label in labels]							,   return_tensors="pt"							,   padding="max_length"							,   )







 def 					__lowercase					(		self					:   Optional[Any]							,   SCREAMING_SNAKE_CASE					:   Dict						):


      '''simple docstring'''






      UpperCamelCase__			:   List[Any]       				=  outputs.logits
      UpperCamelCase__			:   Any       				=  torch.argmax(logits[:, 2]						).item()
      return self._labels[label_id]