
"""simple docstring"""

import html

from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...utils import is_bsa_available, logging, requires_backends


if is_bsa_available():
   import bsa
   from bsa import BeautifulSoup


SCREAMING_SNAKE_CASE_            =    logging.get_logger(__name__)
class   _UpperCAmelCase				(		__a				):




      def __init__(				self ,							**lowercase_				)    ->       List[Any]:
          requires_backends(self ,							['bs4']				)
          super().__init__(**_lowerCamelCase				)




      def      a_   (				self ,							lowercase_				)    ->       Tuple:
          UpperCAmelCase          =       []
          UpperCAmelCase          =       []
          UpperCAmelCase          =       element if element.name else element.parent
          for parent in child.parents:  # type: bs4.element.Tag
              UpperCAmelCase          =       parent.find_all(child.name ,							recursive=_lowerCamelCase				)
              xpath_tags.append(child.name				)
              xpath_subscripts.append(
                  0 if 1 == len(_lowerCamelCase				) else next(i for i, s in enumerate(_lowerCamelCase ,							1				) if s is child				)				)
              UpperCAmelCase          =       parent
          xpath_tags.reverse()
          xpath_subscripts.reverse()
          return xpath_tags, xpath_subscripts




      def      a_   (				self ,							lowercase_				)    ->       Union[str, Any]:
          UpperCAmelCase          =       BeautifulSoup(_lowerCamelCase ,							'html.parser'				)

          UpperCAmelCase          =       []
          UpperCAmelCase          =       []
          UpperCAmelCase          =       []

          for element in html_code.descendants:
              if type(_lowerCamelCase				) == bsa.element.NavigableString:
                  if type(element.parent				) != bsa.element.Tag:
                      continue

                  UpperCAmelCase          =       html.unescape(_lowerCamelCase				).strip()
                  if not text_in_this_tag:
                      continue

                  all_doc_strings.append(_lowerCamelCase				)

                  UpperCAmelCase      ,				UpperCAmelCase          =       self.xpath_soup(_lowerCamelCase				)
                  stringaxtag_seq.append(_lowerCamelCase				)
                  stringaxsubs_seq.append(_lowerCamelCase				)

          if len(_lowerCamelCase				) != len(_lowerCamelCase				):
              raise ValueError('Number of doc strings and xtags does not correspond'				)
          if len(_lowerCamelCase				) != len(_lowerCamelCase				):
              raise ValueError('Number of doc strings and xsubs does not correspond'				)

          return all_doc_strings, stringaxtag_seq, stringaxsubs_seq




      def      a_   (				self ,							lowercase_ ,							lowercase_				)    ->       Tuple:
          UpperCAmelCase          =       ''
          for tagname, subs in zip(_lowerCamelCase ,							_lowerCamelCase				):
              xpath += F"/{tagname}"
              if subs != 0:
                  xpath += F"[{subs}]"
          return xpath




      def __call__(				self ,							lowercase_				)    ->       BatchFeature:
          UpperCAmelCase          =       False

          # Check that strings has a valid type
          if isinstance(_lowerCamelCase ,							_lowerCamelCase				):
              UpperCAmelCase          =       True
          elif isinstance(_lowerCamelCase ,							(list, tuple)				):
              if len(_lowerCamelCase				) == 0 or isinstance(html_strings[0] ,							_lowerCamelCase				):
                  UpperCAmelCase          =       True

          if not valid_strings:
              raise ValueError(
                  'HTML strings must of type `str`, `List[str]` (batch of examples), '
                  F"but is of type {type(_lowerCamelCase				)}."				)

          UpperCAmelCase          =       bool(isinstance(_lowerCamelCase ,							(list, tuple)				) and (isinstance(html_strings[0] ,							_lowerCamelCase				))				)

          if not is_batched:
              UpperCAmelCase          =       [html_strings]

          # Get nodes + xpaths
          UpperCAmelCase          =       []
          UpperCAmelCase          =       []
          for html_string in html_strings:
              UpperCAmelCase      ,				UpperCAmelCase      ,				UpperCAmelCase          =       self.get_three_from_single(_lowerCamelCase				)
              nodes.append(_lowerCamelCase				)
              UpperCAmelCase          =       []
              for node, tag_list, sub_list in zip(_lowerCamelCase ,							_lowerCamelCase ,							_lowerCamelCase				):
                  UpperCAmelCase          =       self.construct_xpath(_lowerCamelCase ,							_lowerCamelCase				)
                  xpath_strings.append(_lowerCamelCase				)
              xpaths.append(_lowerCamelCase				)

          # return as Dict
          UpperCAmelCase          =       {'nodes': nodes, 'xpaths': xpaths}
          UpperCAmelCase          =       BatchFeature(data=_lowerCamelCase ,							tensor_type=_lowerCamelCase				)

          return encoded_inputs





"""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 					__a     ( __a       ):



							'''simple docstring'''







							_lowerCamelCase					:			List[Any]          =   """Wav2Vec2FeatureExtractor"""
							_lowerCamelCase					:			Any          =   """AutoTokenizer"""
							def __init__(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										super().__init__(_lowerCamelCase  ,    _lowerCamelCase       )
										__lowercase       =       self.feature_extractor
										__lowercase       =       False
							@classmethod
							def   SCREAMING_SNAKE_CASE						(     cls  ,    _lowerCamelCase  ,    **_lowerCamelCase       )			->							Any:




										'''simple docstring'''
										try:
													return super().from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
										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: "  ,    _lowerCamelCase  ,    )

													__lowercase       =       WavaVecaFeatureExtractor.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
													__lowercase       =       WavaVecaCTCTokenizer.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )

													return cls(feature_extractor=_lowerCamelCase  ,    tokenizer=_lowerCamelCase       )
							def __call__(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							List[Any]:




										'''simple docstring'''
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor(*_lowerCamelCase  ,    **_lowerCamelCase       )

										if "raw_speech" in kwargs:
													warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."       )
													__lowercase       =       kwargs.pop("raw_speech"       )
										else:
													__lowercase       =       kwargs.pop("audio"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("sampling_rate"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("text"  ,    _lowerCamelCase       )
										if len(_lowerCamelCase       ) > 0:
													__lowercase       =       args[0]
													__lowercase       =       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:
													__lowercase       =       self.feature_extractor(_lowerCamelCase  ,    *_lowerCamelCase  ,    sampling_rate=_lowerCamelCase  ,    **_lowerCamelCase       )
										if text is not None:
													__lowercase       =       self.tokenizer(_lowerCamelCase  ,    **_lowerCamelCase       )

										if text is None:
													return inputs
										elif audio is None:
													return encodings
										else:
													__lowercase       =       encodings["input_ids"]
													return inputs
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor.pad(*_lowerCamelCase  ,    **_lowerCamelCase       )

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

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

										if labels is None:
													return input_features
										elif input_features is None:
													return labels
										else:
													__lowercase       =       labels["input_ids"]
													return input_features
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							Optional[int]:




										'''simple docstring'''
										return self.tokenizer.batch_decode(*_lowerCamelCase  ,    **_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							Dict:




										'''simple docstring'''
										return self.tokenizer.decode(*_lowerCamelCase  ,    **_lowerCamelCase       )





							@contextmanager
							def   SCREAMING_SNAKE_CASE						(     self       )			->							str:




										'''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."       )
										__lowercase       =       True
										__lowercase       =       self.tokenizer
										yield
										__lowercase       =       self.feature_extractor
										__lowercase       =       False





