

import unittest

import numpy as np

from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
from transformers.pipelines import AudioClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torchaudio,
    slow,
)

from .test_pipelines_common import ANY






@is_pipeline_test
class _UpperCamelCase							(							unittest.TestCase   ):
			'''simple docstring'''







			lowerCamelCase__           =MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
			lowerCamelCase__           =TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
			def 							__UpperCamelCase (			self							: Optional[Any]      ,      a							: Tuple      ,      a							: Union[str, Any]      ,      a							: Optional[Any]	)							->       Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[str]				     =       AudioClassificationPipeline(model=a      ,      feature_extractor=a	)

				# test with a raw waveform
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       np.zeros((3_4000,)	)
				SCREAMING_SNAKE_CASE   :      List[str]				     =       np.zeros((1_4000,)	)
				return audio_classifier, [audioa, audio]
			def 							__UpperCamelCase (			self							: Dict      ,      a							: str      ,      a							: Union[str, Any]	)							->       int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      Any				     =       examples
				SCREAMING_SNAKE_CASE   :      Dict				     =       audio_classifier(a	)
				# by default a model is initialized with num_labels=2
				self.assertEqual(
				    a      ,      [
				        {"score": ANY(a	), "label": ANY(a	)},
				        {"score": ANY(a	), "label": ANY(a	)},
				    ]      ,      )
				SCREAMING_SNAKE_CASE   :      Dict				     =       audio_classifier(a      ,      top_k=1	)
				self.assertEqual(
				    a      ,      [
				        {"score": ANY(a	), "label": ANY(a	)},
				    ]      ,      )

				self.run_torchaudio(a	)
			@require_torchaudio
			def 							__UpperCamelCase (			self							: str      ,      a							: Optional[int]	)							->       Union[str, Any]:

				"""simple docstring"""

				import datasets

				# test with a local file
				SCREAMING_SNAKE_CASE   :      Tuple				     =       datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy"      ,      "clean"      ,      split="validation"	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       dataset[0]["audio"]["array"]
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       audio_classifier(a	)
				self.assertEqual(
				    a      ,      [
				        {"score": ANY(a	), "label": ANY(a	)},
				        {"score": ANY(a	), "label": ANY(a	)},
				    ]      ,      )
			@require_torch
			def 							__UpperCamelCase (			self							: Union[str, Any]	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       "anton-l/wav2vec2-random-tiny-classifier"

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       pipeline("audio-classification"      ,      model=a	)

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       np.ones((8000,)	)
				SCREAMING_SNAKE_CASE   :      Dict				     =       audio_classifier(a      ,      top_k=4	)

				SCREAMING_SNAKE_CASE   :      List[str]				     =       [
				    {"score": 0.0842, "label": "no"},
				    {"score": 0.0838, "label": "up"},
				    {"score": 0.0837, "label": "go"},
				    {"score": 0.0834, "label": "right"},
				]
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       [
				    {"score": 0.0845, "label": "stop"},
				    {"score": 0.0844, "label": "on"},
				    {"score": 0.0841, "label": "right"},
				    {"score": 0.0834, "label": "left"},
				]
				self.assertIn(nested_simplify(a      ,      decimals=4	)      ,      [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]	)

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       {"array": np.ones((8000,)	), "sampling_rate": audio_classifier.feature_extractor.sampling_rate}
				SCREAMING_SNAKE_CASE   :      Any				     =       audio_classifier(a      ,      top_k=4	)
				self.assertIn(nested_simplify(a      ,      decimals=4	)      ,      [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]	)
			@require_torch
			@slow
			def 							__UpperCamelCase (			self							: int	)							->       List[str]:

				"""simple docstring"""

				import datasets

				SCREAMING_SNAKE_CASE   :      Dict				     =       "superb/wav2vec2-base-superb-ks"

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       pipeline("audio-classification"      ,      model=a	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       datasets.load_dataset("anton-l/superb_dummy"      ,      "ks"      ,      split="test"	)

				SCREAMING_SNAKE_CASE   :      Dict				     =       np.array(dataset[3]["speech"]      ,      dtype=np.floataa	)
				SCREAMING_SNAKE_CASE   :      List[str]				     =       audio_classifier(a      ,      top_k=4	)
				self.assertEqual(
				    nested_simplify(a      ,      decimals=3	)      ,      [
				        {"score": 0.981, "label": "go"},
				        {"score": 0.007, "label": "up"},
				        {"score": 0.006, "label": "_unknown_"},
				        {"score": 0.001, "label": "down"},
				    ]      ,      )






			@require_tf
			@unittest.skip("Audio classification is not implemented for TF"	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Dict:

				"""simple docstring"""

				pass


import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


a_						     =    datasets.utils.logging.get_logger(__name__)






@dataclass
class _UpperCamelCase							(							datasets.BuilderConfig   ):
			'''simple docstring'''







			lowerCamelCase__           =10000
			lowerCamelCase__           =None
			lowerCamelCase__           =None






class _UpperCamelCase							(							datasets.ArrowBasedBuilder   ):
			'''simple docstring'''







			lowerCamelCase__           =ParquetConfig
			def 							__UpperCamelCase (			self							: str	)							->       str:

				"""simple docstring"""

				return datasets.DatasetInfo(features=self.config.features	)
			def 							__UpperCamelCase (			self							: Dict      ,      a							: List[Any]	)							->       Tuple:

				"""simple docstring"""

				if not self.config.data_files:
					raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}"	)
				SCREAMING_SNAKE_CASE   :      Tuple				     =       dl_manager.download_and_extract(self.config.data_files	)
				if isinstance(a      ,      (str, list, tuple)	):
					SCREAMING_SNAKE_CASE   :      Dict				     =       data_files
					if isinstance(a      ,      a	):
						SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       [files]
					# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
					SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       [dl_manager.iter_files(a	) for file in files]
					return [datasets.SplitGenerator(name=datasets.Split.TRAIN      ,      gen_kwargs={"files": files}	)]
				SCREAMING_SNAKE_CASE   :      str				     =       []
				for split_name, files in data_files.items():
					if isinstance(a      ,      a	):
						SCREAMING_SNAKE_CASE   :      Optional[int]				     =       [files]
					# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
					SCREAMING_SNAKE_CASE   :      Tuple				     =       [dl_manager.iter_files(a	) for file in files]
					# Infer features is they are stoed in the arrow schema
					if self.info.features is None:
						for file in itertools.chain.from_iterable(a	):
							with open(a      ,      "rb"	) as f:
								SCREAMING_SNAKE_CASE   :      Dict				     =       datasets.Features.from_arrow_schema(pq.read_schema(a	)	)
							break
					splits.append(datasets.SplitGenerator(name=a      ,      gen_kwargs={"files": files}	)	)
				return splits
			def 							__UpperCamelCase (			self							: Dict      ,      a							: pa.Table	)							->       pa.Table:

				"""simple docstring"""

				if self.info.features is not None:
					# more expensive cast to support nested features with keys in a different order
					# allows str <-> int/float or str to Audio for example
					SCREAMING_SNAKE_CASE   :      str				     =       table_cast(a      ,      self.info.features.arrow_schema	)
				return pa_table






			def 							__UpperCamelCase (			self							: List[str]      ,      a							: Optional[Any]	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Any				     =       self.info.features.arrow_schema if self.info.features is not None else None
				if self.info.features is not None and self.config.columns is not None:
					if sorted(field.name for field in schema	) != sorted(self.config.columns	):
						raise ValueError(
						    F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'"	)
				for file_idx, file in enumerate(itertools.chain.from_iterable(a	)	):
					with open(a      ,      "rb"	) as f:
						SCREAMING_SNAKE_CASE   :      Optional[int]				     =       pq.ParquetFile(a	)
						try:
							for batch_idx, record_batch in enumerate(
							    parquet_file.iter_batches(batch_size=self.config.batch_size      ,      columns=self.config.columns	)	):
								SCREAMING_SNAKE_CASE   :      int				     =       pa.Table.from_batches([record_batch]	)
								# Uncomment for debugging (will print the Arrow table size and elements)
								# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
								# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
								yield F"{file_idx}_{batch_idx}", self._cast_table(a	)
						except ValueError as e:
							logger.error(F"Failed to read file '{file}' with error {type(a	)}: {e}"	)
							raise