'''simple docstring'''





import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer







class __snake_case       (		lowerCamelCase_	):
   lowerCAmelCase_														=							"Wav2Vec2FeatureExtractor"
   lowerCAmelCase_														=							"AutoTokenizer"




   def __init__(					self    :       Dict ,			_lowercase    :       Union[str, Any] ,			_lowercase    :       str   ):



     """simple docstring"""






     super().__init__(_lowercase ,			_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   self.feature_extractor
     SCREAMING_SNAKE_CASE__    							=   False




   @classmethod
   def 			__a		(					cls    :       Any ,			_lowercase    :       Dict ,			**_lowercase    :       Optional[int]   ):



     """simple docstring"""






     try:
       return super().from_pretrained(_lowercase ,			**_lowercase   )
     except OSError:
       warnings.warn(
           f"""Loading a tokenizer inside {cls.__name__} from a config that does not"""
           """ include a `tokenizer_class` attribute is deprecated and will be """
           """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`"""
           """ attribute to either your `config.json` or `tokenizer_config.json` """
           """file to suppress this warning: """ ,			_lowercase ,			)

       SCREAMING_SNAKE_CASE__    							=   WavaVecaFeatureExtractor.from_pretrained(_lowercase ,			**_lowercase   )
       SCREAMING_SNAKE_CASE__    							=   WavaVecaCTCTokenizer.from_pretrained(_lowercase ,			**_lowercase   )

       return cls(feature_extractor=_lowercase ,			tokenizer=_lowercase   )




   def __call__(					self    :       Any ,			*_lowercase    :       Optional[Any] ,			**_lowercase    :       Dict   ):



     """simple docstring"""






     if self._in_target_context_manager:
       return self.current_processor(*_lowercase ,			**_lowercase   )

     if "raw_speech" in kwargs:
       warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."""   )
       SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""raw_speech"""   )
     else:
       SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""audio""" ,			_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""sampling_rate""" ,			_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""text""" ,			_lowercase   )
     if len(_lowercase   ) > 0:
       SCREAMING_SNAKE_CASE__    							=   args[0]
       SCREAMING_SNAKE_CASE__    							=   args[1:]

     if audio is None and text is None:
       raise ValueError("""You need to specify either an `audio` or `text` input to process."""   )

     if audio is not None:
       SCREAMING_SNAKE_CASE__    							=   self.feature_extractor(_lowercase ,			*_lowercase ,			sampling_rate=_lowercase ,			**_lowercase   )
     if text is not None:
       SCREAMING_SNAKE_CASE__    							=   self.tokenizer(_lowercase ,			**_lowercase   )

     if text is None:
       return inputs
     elif audio is None:
       return encodings
     else:
       SCREAMING_SNAKE_CASE__    							=   encodings["""input_ids"""]
       return inputs




   def 			__a		(					self    :       Tuple ,			*_lowercase    :       Tuple ,			**_lowercase    :       int   ):



     """simple docstring"""






     if self._in_target_context_manager:
       return self.current_processor.pad(*_lowercase ,			**_lowercase   )

     SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""input_features""" ,			_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""labels""" ,			_lowercase   )
     if len(_lowercase   ) > 0:
       SCREAMING_SNAKE_CASE__    							=   args[0]
       SCREAMING_SNAKE_CASE__    							=   args[1:]

     if input_features is not None:
       SCREAMING_SNAKE_CASE__    							=   self.feature_extractor.pad(_lowercase ,			*_lowercase ,			**_lowercase   )
     if labels is not None:
       SCREAMING_SNAKE_CASE__    							=   self.tokenizer.pad(_lowercase ,			**_lowercase   )

     if labels is None:
       return input_features
     elif input_features is None:
       return labels
     else:
       SCREAMING_SNAKE_CASE__    							=   labels["""input_ids"""]
       return input_features




   def 			__a		(					self    :       Any ,			*_lowercase    :       int ,			**_lowercase    :       int   ):



     """simple docstring"""






     return self.tokenizer.batch_decode(*_lowercase ,			**_lowercase   )




   def 			__a		(					self    :       int ,			*_lowercase    :       str ,			**_lowercase    :       Tuple   ):



     """simple docstring"""






     return self.tokenizer.decode(*_lowercase ,			**_lowercase   )




   @contextmanager
   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     warnings.warn(
         """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
         """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
         """your audio inputs, or in a separate call."""   )
     SCREAMING_SNAKE_CASE__    							=   True
     SCREAMING_SNAKE_CASE__    							=   self.tokenizer
     yield
     SCREAMING_SNAKE_CASE__    							=   self.feature_extractor
     SCREAMING_SNAKE_CASE__    							=   False

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


__lowerCamelCase    :				Union[str, Any]							     =	datasets.utils.logging.get_logger(__name__)







@dataclass
class __snake_case       (		datasets.BuilderConfig	):
   lowerCAmelCase_														=							1_00_00
   lowerCAmelCase_														=							None
   lowerCAmelCase_														=							None







class __snake_case       (		datasets.ArrowBasedBuilder	):
   lowerCAmelCase_														=							ParquetConfig




   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






     return datasets.DatasetInfo(features=self.config.features   )




   def 			__a		(					self    :       Dict ,			_lowercase    :       List[str]   ):



     """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__    							=   dl_manager.download_and_extract(self.config.data_files   )
     if isinstance(_lowercase ,			(str, list, tuple)   ):
       SCREAMING_SNAKE_CASE__    							=   data_files
       if isinstance(_lowercase ,			_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   [files]
       # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
       SCREAMING_SNAKE_CASE__    							=   [dl_manager.iter_files(_lowercase   ) for file in files]
       return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,			gen_kwargs={"""files""": files}   )]
     SCREAMING_SNAKE_CASE__    							=   []
     for split_name, files in data_files.items():
       if isinstance(_lowercase ,			_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   [files]
       # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
       SCREAMING_SNAKE_CASE__    							=   [dl_manager.iter_files(_lowercase   ) 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(_lowercase   ):
           with open(_lowercase ,			"""rb"""   ) as f:
             SCREAMING_SNAKE_CASE__    							=   datasets.Features.from_arrow_schema(pq.read_schema(_lowercase   )   )
           break
       splits.append(datasets.SplitGenerator(name=_lowercase ,			gen_kwargs={"""files""": files}   )   )
     return splits




   def 			__a		(					self    :       Optional[Any] ,			_lowercase    :       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__    							=   table_cast(_lowercase ,			self.info.features.arrow_schema   )
     return pa_table




   def 			__a		(					self    :       Dict ,			_lowercase    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   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(_lowercase   )   ):
       with open(_lowercase ,			"""rb"""   ) as f:
         SCREAMING_SNAKE_CASE__    							=   pq.ParquetFile(_lowercase   )
         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__    							=   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(_lowercase   )
         except ValueError as e:
           logger.error(f"""Failed to read file '{file}' with error {type(_lowercase   )}: {e}"""   )
           raise
