


'''simple docstring'''

import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCAmelCase				:Any        =      random.Random()





def lowerCamelCase      (      lowerCAmelCase    :     Tuple		,		lowerCAmelCase    :     int=1.0		,		lowerCAmelCase    :     int=None		,		lowerCAmelCase    :     List[Any]=None		):





	"""simple docstring"""







	if rng is None:
		__magic_name__	:   List[str]					     =					global_rng

	__magic_name__	:   List[str]					     =					[]
	for batch_idx in range(shape[0]		):
		values.append([]		)
		for _ in range(shape[1]		):
			values[-1].append(rng.random() * scale		)

	return values
class _lowerCamelCase	(						unittest.TestCase							):



		'''simple docstring'''







		def __init__( self		:						Optional[Any]  ,					_A		:						int  ,					_A		:						str=7  ,					_A		:						Optional[Any]=400  ,					_A		:						List[Any]=2000  ,					_A		:						Optional[Any]=1  ,					_A		:						Optional[Any]=0.0  ,					_A		:						int=16000  ,					_A		:						int=True  ,					_A		:						List[str]=True  ,					)  ->			int:
			__magic_name__	:   Optional[int]					     =					parent
			__magic_name__	:   Dict					     =					batch_size
			__magic_name__	:   str					     =					min_seq_length
			__magic_name__	:   Tuple					     =					max_seq_length
			__magic_name__	:   List[Any]					     =					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
			__magic_name__	:   Optional[int]					     =					feature_size
			__magic_name__	:   List[Any]					     =					padding_value
			__magic_name__	:   Tuple					     =					sampling_rate
			__magic_name__	:   List[str]					     =					return_attention_mask
			__magic_name__	:   Union[str, Any]					     =					do_normalize







		def        __lowerCAmelCase		( self		:						int      )  ->			int:
			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        __lowerCAmelCase		( self		:						List[Any]  ,					_A		:						List[str]=False  ,					_A		:						Union[str, Any]=False      )  ->			str:
			def _flatten(_A		:						int      ):
				return list(itertools.chain(*_A      )      )

			if equal_length:
				__magic_name__	:   Dict					     =					floats_list((self.batch_size, self.max_seq_length)      )
			else:
				# make sure that inputs increase in size
				__magic_name__	:   Tuple					     =					[
				    _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:
				__magic_name__	:   Optional[int]					     =					[np.asarray(_A      ) for x in speech_inputs]

			return speech_inputs







class _lowerCamelCase	(						lowercase__		,					unittest.TestCase							):



		'''simple docstring'''







		A_     :      List[str]				   =    WavaVecaFeatureExtractor







		def        __lowerCAmelCase		( self		:						str      )  ->			Optional[int]:
			__magic_name__	:   str					     =					WavaVecaFeatureExtractionTester(self      )







		def        __lowerCAmelCase		( self		:						Optional[Any]  ,					_A		:						List[Any]      )  ->			Any:
			self.assertTrue(np.all(np.mean(_A  ,					axis=0      ) < 1E-3      )      )
			self.assertTrue(np.all(np.abs(np.var(_A  ,					axis=0      ) - 1      ) < 1E-3      )      )







		def        __lowerCAmelCase		( self		:						List[Any]      )  ->			Optional[Any]:
			# Tests that all call wrap to encode_plus and batch_encode_plus
			__magic_name__	:   Optional[int]					     =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
			# create three inputs of length 800, 1000, and 1200
			__magic_name__	:   Union[str, Any]					     =					[floats_list((1, x)      )[0] for x in range(800  ,					1400  ,					200      )]
			__magic_name__	:   Union[str, Any]					     =					[np.asarray(_A      ) for speech_input in speech_inputs]

			# Test not batched input
			__magic_name__	:   List[Any]					     =					feat_extract(speech_inputs[0]  ,					return_tensors='np'      ).input_values
			__magic_name__	:   Optional[Any]					     =					feat_extract(np_speech_inputs[0]  ,					return_tensors='np'      ).input_values
			self.assertTrue(np.allclose(_A  ,					_A  ,					atol=1E-3      )      )

			# Test batched
			__magic_name__	:   Tuple					     =					feat_extract(_A  ,					return_tensors='np'      ).input_values
			__magic_name__	:   str					     =					feat_extract(_A  ,					return_tensors='np'      ).input_values
			for enc_seq_a, enc_seq_a in zip(_A  ,					_A      ):
				self.assertTrue(np.allclose(_A  ,					_A  ,					atol=1E-3      )      )

			# Test 2-D numpy arrays are batched.
			__magic_name__	:   Optional[int]					     =					[floats_list((1, x)      )[0] for x in (800, 800, 800)]
			__magic_name__	:   Optional[int]					     =					np.asarray(_A      )
			__magic_name__	:   List[Any]					     =					feat_extract(_A  ,					return_tensors='np'      ).input_values
			__magic_name__	:   List[Any]					     =					feat_extract(_A  ,					return_tensors='np'      ).input_values
			for enc_seq_a, enc_seq_a in zip(_A  ,					_A      ):
				self.assertTrue(np.allclose(_A  ,					_A  ,					atol=1E-3      )      )







		def        __lowerCAmelCase		( self		:						List[Any]      )  ->			Tuple:
			__magic_name__	:   str					     =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
			__magic_name__	:   Any					     =					[floats_list((1, x)      )[0] for x in range(800  ,					1400  ,					200      )]

			__magic_name__	:   int					     =					['longest', 'max_length', 'do_not_pad']
			__magic_name__	:   Any					     =					[None, 1600, None]
			for max_length, padding in zip(_A  ,					_A      ):
				__magic_name__	:   List[str]					     =					feat_extract(_A  ,					padding=_A  ,					max_length=_A  ,					return_tensors='np'      )
				__magic_name__	:   List[Any]					     =					processed.input_values

				self._check_zero_mean_unit_variance(input_values[0][:800]      )
				self.assertTrue(input_values[0][800:].sum() < 1E-6      )
				self._check_zero_mean_unit_variance(input_values[1][:1000]      )
				self.assertTrue(input_values[0][1000:].sum() < 1E-6      )
				self._check_zero_mean_unit_variance(input_values[2][:1200]      )







		def        __lowerCAmelCase		( self		:						Optional[int]      )  ->			List[str]:
			__magic_name__	:   Dict					     =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
			__magic_name__	:   List[str]					     =					range(800  ,					1400  ,					200      )
			__magic_name__	:   Optional[Any]					     =					[floats_list((1, x)      )[0] for x in lengths]

			__magic_name__	:   Tuple					     =					['longest', 'max_length', 'do_not_pad']
			__magic_name__	:   Any					     =					[None, 1600, None]

			for max_length, padding in zip(_A  ,					_A      ):
				__magic_name__	:   str					     =					feat_extract(_A  ,					max_length=_A  ,					padding=_A      )
				__magic_name__	:   List[Any]					     =					processed.input_values

				self._check_zero_mean_unit_variance(input_values[0][:800]      )
				self._check_zero_mean_unit_variance(input_values[1][:1000]      )
				self._check_zero_mean_unit_variance(input_values[2][:1200]      )







		def        __lowerCAmelCase		( self		:						List[Any]      )  ->			Dict:
			__magic_name__	:   Union[str, Any]					     =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
			__magic_name__	:   Any					     =					[floats_list((1, x)      )[0] for x in range(800  ,					1400  ,					200      )]
			__magic_name__	:   Optional[Any]					     =					feat_extract(
			    _A  ,					truncation=_A  ,					max_length=1000  ,					padding='max_length'  ,					return_tensors='np'      )
			__magic_name__	:   Optional[int]					     =					processed.input_values

			self._check_zero_mean_unit_variance(input_values[0, :800]      )
			self._check_zero_mean_unit_variance(input_values[1]      )
			self._check_zero_mean_unit_variance(input_values[2]      )







		def        __lowerCAmelCase		( self		:						Any      )  ->			Dict:
			__magic_name__	:   Dict					     =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
			__magic_name__	:   List[str]					     =					[floats_list((1, x)      )[0] for x in range(800  ,					1400  ,					200      )]
			__magic_name__	:   Optional[int]					     =					feat_extract(
			    _A  ,					truncation=_A  ,					max_length=1000  ,					padding='longest'  ,					return_tensors='np'      )
			__magic_name__	:   Optional[int]					     =					processed.input_values

			self._check_zero_mean_unit_variance(input_values[0, :800]      )
			self._check_zero_mean_unit_variance(input_values[1, :1000]      )
			self._check_zero_mean_unit_variance(input_values[2]      )

			# make sure that if max_length < longest -> then pad to max_length
			self.assertTrue(input_values.shape == (3, 1000)      )

			__magic_name__	:   Optional[int]					     =					[floats_list((1, x)      )[0] for x in range(800  ,					1400  ,					200      )]
			__magic_name__	:   str					     =					feat_extract(
			    _A  ,					truncation=_A  ,					max_length=2000  ,					padding='longest'  ,					return_tensors='np'      )
			__magic_name__	:   Optional[int]					     =					processed.input_values

			self._check_zero_mean_unit_variance(input_values[0, :800]      )
			self._check_zero_mean_unit_variance(input_values[1, :1000]      )
			self._check_zero_mean_unit_variance(input_values[2]      )

			# make sure that if max_length > longest -> then pad to longest
			self.assertTrue(input_values.shape == (3, 1200)      )







		@require_torch
		def        __lowerCAmelCase		( self		:						Optional[int]      )  ->			Any:
			import torch

			__magic_name__	:   List[Any]					     =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
			__magic_name__	:   List[str]					     =					np.random.rand(100      ).astype(np.floataa      )
			__magic_name__	:   Union[str, Any]					     =					np_speech_inputs.tolist()

			for inputs in [py_speech_inputs, np_speech_inputs]:
				__magic_name__	:   Optional[int]					     =					feature_extractor.pad([{'input_values': inputs}]  ,					return_tensors='np'      )
				self.assertTrue(np_processed.input_values.dtype == np.floataa      )
				__magic_name__	:   Dict					     =					feature_extractor.pad([{'input_values': inputs}]  ,					return_tensors='pt'      )
				self.assertTrue(pt_processed.input_values.dtype == torch.floataa      )







		@slow
		@require_torch
		def        __lowerCAmelCase		( self		:						int      )  ->			int:
			# this test makes sure that models that are using
			# group norm don't have their feature extractor return the
			# attention_mask
			for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
				__magic_name__	:   Any					     =					WavaVecaConfig.from_pretrained(_A      )
				__magic_name__	:   str					     =					WavaVecaFeatureExtractor.from_pretrained(_A      )

				# only "layer" feature extraction norm should make use of
				# attention_mask
				self.assertEqual(feat_extract.return_attention_mask  ,					config.feat_extract_norm == 'layer'      )



'''simple docstring'''

# 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.
from typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
							from PIL import Image
class _lowerCamelCase	(						lowercase__							):



		'''simple docstring'''







		A_     :      Any				   =    """Salesforce/blip-image-captioning-base"""
		A_     :      Any				   =    (
		    """This is a tool that generates a description of an image. It takes an input named `image` which should be the """
		    """image to caption, and returns a text that contains the description in English."""
		)
		A_     :      List[str]				   =    """image_captioner"""
		A_     :      Optional[Any]				   =    AutoModelForVisionaSeq

		A_     :      Any				   =    ["""image"""]
		A_     :      Union[str, Any]				   =    ["""text"""]







		def __init__( self		:						Dict  ,					*_A		:						Dict  ,					**_A		:						Any      )  ->			Dict:
			requires_backends(self  ,					['vision']      )
			super().__init__(*_A  ,					**_A      )







		def        __lowerCAmelCase		( self		:						Tuple  ,					_A		:						"Image"      )  ->			Union[str, Any]:
			return self.pre_processor(images=_A  ,					return_tensors='pt'      )







		def        __lowerCAmelCase		( self		:						Optional[Any]  ,					_A		:						str      )  ->			List[Any]:
			return self.model.generate(**_A      )







		def        __lowerCAmelCase		( self		:						int  ,					_A		:						Optional[int]      )  ->			Union[str, Any]:
			return self.pre_processor.batch_decode(_A  ,					skip_special_tokens=_A      )[0].strip()