





'''simple docstring'''






from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


lowerCAmelCase     :   Optional[int]       		=      logging.get_logger(__name__)
@add_end_docstrings(_A       )
class 		lowerCamelCase  (      _A       ):



	def __init__(   self		,      **a_	):
			super().__init__(**a_	)

			if self.framework != "pt":
					raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''	)
			# No specific FOR_XXX available yet



	def __call__(   self		,      a_		,      **a_	):
			return super().__call__(a_		,      **a_	)



	def   _lowerCamelCase    (   self		,      **a_	):
			lowerCAmelCase     :    List[Any]						=   {}
			if "candidate_labels" in kwargs:
					lowerCAmelCase     :    int						=   kwargs["candidate_labels"]
			if "hypothesis_template" in kwargs:
					lowerCAmelCase     :    Optional[Any]						=   kwargs["hypothesis_template"]

			return preprocess_params, {}, {}



	def   _lowerCamelCase    (   self		,      a_		,      a_=None		,      a_="This is a sound of {}."	):
			if isinstance(a_		,      a_	):
					if audio.startswith("http://"	) or audio.startswith("https://"	):
							# We need to actually check for a real protocol, otherwise it's impossible to use a local file
							# like http_huggingface_co.png
							lowerCAmelCase     :    Optional[int]						=   requests.get(a_	).content
					else:
							with open(a_		,      "rb"	) as f:
									lowerCAmelCase     :    Optional[int]						=   f.read()

			if isinstance(a_		,      a_	):
					lowerCAmelCase     :    Optional[Any]						=   ffmpeg_read(a_		,      self.feature_extractor.sampling_rate	)

			if not isinstance(a_		,      np.ndarray	):
					raise ValueError("We expect a numpy ndarray as input"	)
			if len(audio.shape	) != 1:
					raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline"	)

			lowerCAmelCase     :    Dict						=   self.feature_extractor(
			    [audio]		,      sampling_rate=self.feature_extractor.sampling_rate		,      return_tensors="pt"	)
			lowerCAmelCase     :    List[Any]						=   candidate_labels
			lowerCAmelCase     :    Optional[int]						=   [hypothesis_template.format(a_	) for x in candidate_labels]
			lowerCAmelCase     :    str						=   self.tokenizer(a_		,      return_tensors=self.framework		,      padding=a_	)
			lowerCAmelCase     :    List[str]						=   [text_inputs]
			return inputs



	def   _lowerCamelCase    (   self		,      a_	):
			lowerCAmelCase     :    str						=   model_inputs.pop("candidate_labels"	)
			lowerCAmelCase     :    int						=   model_inputs.pop("text_inputs"	)
			if isinstance(text_inputs[0]		,      a_	):
					lowerCAmelCase     :    str						=   text_inputs[0]
			else:
					# Batching case.
					lowerCAmelCase     :    Optional[Any]						=   text_inputs[0][0]

			lowerCAmelCase     :    Tuple						=   self.model(**a_		,      **a_	)

			lowerCAmelCase     :    Any						=   {
			    "candidate_labels": candidate_labels,
			    "logits": outputs.logits_per_audio,
			}
			return model_outputs





	def   _lowerCamelCase    (   self		,      a_	):
			lowerCAmelCase     :    List[str]						=   model_outputs.pop("candidate_labels"	)
			lowerCAmelCase     :    List[Any]						=   model_outputs["logits"][0]

			if self.framework == "pt":
					lowerCAmelCase     :    Optional[Any]						=   logits.softmax(dim=0	)
					lowerCAmelCase     :    int						=   probs.tolist()
			else:
					raise ValueError("`tf` framework not supported."	)

			lowerCAmelCase     :    Optional[Any]						=   [
			    {"score": score, "label": candidate_label}
			    for score, candidate_label in sorted(zip(a_		,      a_	)		,      key=lambda a_	: -x[0]	)
			]
			return result










'''simple docstring'''






import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
					import tensorflow as tf

					from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments
@require_tf
class 		lowerCamelCase  (      unittest.TestCase       ):



	def   _lowerCamelCase    (   self		,      a_	):
			for model_result in results.values():
					for batch_size, sequence_length in zip(model_result["bs"]		,      model_result["ss"]	):
							lowerCAmelCase     :    Tuple						=   model_result["result"][batch_size][sequence_length]
							self.assertIsNotNone(a_	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Optional[int]						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    Tuple						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      eager_mode=a_		,      multi_process=a_		,      )
			lowerCAmelCase     :    Optional[Any]						=   TensorFlowBenchmark(a_	)
			lowerCAmelCase     :    Optional[Any]						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Union[str, Any]						=   "sgugger/tiny-distilbert-classification"
			lowerCAmelCase     :    Tuple						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      multi_process=a_		,      only_pretrain_model=a_		,      )
			lowerCAmelCase     :    Any						=   TensorFlowBenchmark(a_	)
			lowerCAmelCase     :    str						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Union[str, Any]						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    str						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      multi_process=a_		,      )
			lowerCAmelCase     :    List[str]						=   TensorFlowBenchmark(a_	)
			lowerCAmelCase     :    str						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    List[str]						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    Union[str, Any]						=   AutoConfig.from_pretrained(a_	)
			lowerCAmelCase     :    Optional[Any]						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      eager_mode=a_		,      multi_process=a_		,      )
			lowerCAmelCase     :    Any						=   TensorFlowBenchmark(a_		,      [config]	)
			lowerCAmelCase     :    Union[str, Any]						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    int						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    Union[str, Any]						=   AutoConfig.from_pretrained(a_	)
			lowerCAmelCase     :    Union[str, Any]						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      multi_process=a_		,      )
			lowerCAmelCase     :    Tuple						=   TensorFlowBenchmark(a_		,      [config]	)
			lowerCAmelCase     :    Any						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Tuple						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    List[str]						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      multi_process=a_		,      )
			lowerCAmelCase     :    List[str]						=   TensorFlowBenchmark(a_	)
			lowerCAmelCase     :    str						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_train_result	)
			self.check_results_dict_not_empty(results.memory_train_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    List[Any]						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    Union[str, Any]						=   AutoConfig.from_pretrained(a_	)
			lowerCAmelCase     :    Dict						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      multi_process=a_		,      )
			lowerCAmelCase     :    Dict						=   TensorFlowBenchmark(a_		,      [config]	)
			lowerCAmelCase     :    int						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_train_result	)
			self.check_results_dict_not_empty(results.memory_train_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    str						=   "patrickvonplaten/t5-tiny-random"
			lowerCAmelCase     :    Tuple						=   AutoConfig.from_pretrained(a_	)
			lowerCAmelCase     :    Dict						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      multi_process=a_		,      )
			lowerCAmelCase     :    List[str]						=   TensorFlowBenchmark(a_		,      configs=[config]	)
			lowerCAmelCase     :    List[Any]						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	@unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("GPU"	)	) == 0		,      "Cannot do xla on CPU."	)
	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    str						=   "sshleifer/tiny-gpt2"
			lowerCAmelCase     :    List[Any]						=   TensorFlowBenchmarkArguments(
			    models=[MODEL_ID]		,      training=a_		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      use_xla=a_		,      multi_process=a_		,      )
			lowerCAmelCase     :    Any						=   TensorFlowBenchmark(a_	)
			lowerCAmelCase     :    str						=   benchmark.run()
			self.check_results_dict_not_empty(results.time_inference_result	)
			self.check_results_dict_not_empty(results.memory_inference_result	)



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Tuple						=   "sshleifer/tiny-gpt2"
			with tempfile.TemporaryDirectory() as tmp_dir:
					lowerCAmelCase     :    Optional[int]						=   TensorFlowBenchmarkArguments(
					    models=[MODEL_ID]		,      inference=a_		,      save_to_csv=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      inference_time_csv_file=os.path.join(a_		,      "inf_time.csv"	)		,      inference_memory_csv_file=os.path.join(a_		,      "inf_mem.csv"	)		,      env_info_csv_file=os.path.join(a_		,      "env.csv"	)		,      multi_process=a_		,      )
					lowerCAmelCase     :    Optional[Any]						=   TensorFlowBenchmark(a_	)
					benchmark.run()
					self.assertTrue(Path(os.path.join(a_		,      "inf_time.csv"	)	).exists()	)
					self.assertTrue(Path(os.path.join(a_		,      "inf_mem.csv"	)	).exists()	)
					self.assertTrue(Path(os.path.join(a_		,      "env.csv"	)	).exists()	)





	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Any						=   "sshleifer/tiny-gpt2"

			def _check_summary_is_not_empty(a_	):
					self.assertTrue(hasattr(a_		,      "sequential"	)	)
					self.assertTrue(hasattr(a_		,      "cumulative"	)	)
					self.assertTrue(hasattr(a_		,      "current"	)	)
					self.assertTrue(hasattr(a_		,      "total"	)	)

			with tempfile.TemporaryDirectory() as tmp_dir:
					lowerCAmelCase     :    int						=   TensorFlowBenchmarkArguments(
					    models=[MODEL_ID]		,      inference=a_		,      sequence_lengths=[8]		,      batch_sizes=[1]		,      log_filename=os.path.join(a_		,      "log.txt"	)		,      log_print=a_		,      trace_memory_line_by_line=a_		,      eager_mode=a_		,      multi_process=a_		,      )
					lowerCAmelCase     :    Optional[Any]						=   TensorFlowBenchmark(a_	)
					lowerCAmelCase     :    Tuple						=   benchmark.run()
					_check_summary_is_not_empty(result.inference_summary	)
					self.assertTrue(Path(os.path.join(a_		,      "log.txt"	)	).exists()	)



