'''simple docstring'''






import json
import os
import shutil
import tempfile
import unittest
from multiprocessing import get_context
from pathlib import Path

import datasets
import numpy as np
from datasets import load_dataset
from parameterized import parameterized

from transformers import AutoProcessor
from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available

from ..wavaveca.test_feature_extraction_wavaveca import floats_list


if is_pyctcdecode_available():
     from huggingface_hub import snapshot_download
     from pyctcdecode import BeamSearchDecoderCTC

     from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM
     from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput

if is_torch_available():
     from transformers import WavaVecaForCTC





@require_pyctcdecode
class     A__							(       unittest.TestCase   ):





   """simple docstring"""





   def 			_lowerCAmelCase		( self     :		Optional[Any]			)       ->    Tuple:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   '| <pad> <unk> <s> </s> a b c d e f g h i j k'.split()
      _UpperCAmelCase							:	Union[str, Any]							=   dict(zip(_UpperCamelCase						,     range(len(_UpperCamelCase			)			)			)			)

      _UpperCAmelCase							:	Optional[Any]							=   {
          'unk_token': '<unk>',
          'bos_token': '<s>',
          'eos_token': '</s>',
      }
      _UpperCAmelCase							:	str							=   {
          'feature_size': 1,
          'padding_value': 0.0,
          'sampling_rate': 1_6_0_0_0,
          'return_attention_mask': False,
          'do_normalize': True,
      }

      _UpperCAmelCase							:	List[str]							=   tempfile.mkdtemp()
      _UpperCAmelCase							:	List[str]							=   os.path.join(self.tmpdirname						,     VOCAB_FILES_NAMES["vocab_file"]			)
      _UpperCAmelCase							:	int							=   os.path.join(self.tmpdirname						,     _UpperCamelCase			)
      with open(self.vocab_file						,     "w"						,     encoding="utf-8"			) as fp:
         fp.write(json.dumps(_UpperCamelCase			) + "\n"			)

      with open(self.feature_extraction_file						,     "w"						,     encoding="utf-8"			) as fp:
         fp.write(json.dumps(_UpperCamelCase			) + "\n"			)

      # load decoder from hub
      _UpperCAmelCase							:	List[Any]							=   'hf-internal-testing/ngram-beam-search-decoder'




   def 			_lowerCAmelCase		( self     :		int						,     **lowerCAmelCase__     :		List[Any]			)       ->    Union[str, Any]:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[Any]							=   self.add_kwargs_tokens_map.copy()
      kwargs.update(_UpperCamelCase			)
      return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname						,     **_UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Tuple						,     **lowerCAmelCase__     :		int			)       ->    List[Any]:







      """simple docstring"""




      return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname						,     **_UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Any						,     **lowerCAmelCase__     :		List[str]			)       ->    int:







      """simple docstring"""




      return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name						,     **_UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Any			)       ->    str:







      """simple docstring"""




      shutil.rmtree(self.tmpdirname			)




   def 			_lowerCAmelCase		( self     :		Dict			)       ->    Optional[int]:







      """simple docstring"""




      _UpperCAmelCase							:	int							=   self.get_tokenizer()
      _UpperCAmelCase							:	List[str]							=   self.get_feature_extractor()
      _UpperCAmelCase							:	Optional[Any]							=   self.get_decoder()

      _UpperCAmelCase							:	List[str]							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      processor.save_pretrained(self.tmpdirname			)
      _UpperCAmelCase							:	Any							=   WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname			)

      # tokenizer
      self.assertEqual(processor.tokenizer.get_vocab()						,     tokenizer.get_vocab()			)
      self.assertIsInstance(processor.tokenizer						,     _UpperCamelCase			)

      # feature extractor
      self.assertEqual(processor.feature_extractor.to_json_string()						,     feature_extractor.to_json_string()			)
      self.assertIsInstance(processor.feature_extractor						,     _UpperCamelCase			)

      # decoder
      self.assertEqual(processor.decoder._alphabet.labels						,     decoder._alphabet.labels			)
      self.assertEqual(
          processor.decoder.model_container[decoder._model_key]._unigram_set						,     decoder.model_container[decoder._model_key]._unigram_set						,     )
      self.assertIsInstance(processor.decoder						,     _UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Optional[Any]			)       ->    Any:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[Any]							=   WavaVecaProcessorWithLM(
          tokenizer=self.get_tokenizer()						,     feature_extractor=self.get_feature_extractor()						,     decoder=self.get_decoder()			)
      processor.save_pretrained(self.tmpdirname			)

      # make sure that error is thrown when decoder alphabet doesn't match
      _UpperCAmelCase							:	Dict							=   WavaVecaProcessorWithLM.from_pretrained(
          self.tmpdirname						,     alpha=5.0						,     beta=3.0						,     score_boundary=-7.0						,     unk_score_offset=3			)

      # decoder
      self.assertEqual(processor.language_model.alpha						,     5.0			)
      self.assertEqual(processor.language_model.beta						,     3.0			)
      self.assertEqual(processor.language_model.score_boundary						,     -7.0			)
      self.assertEqual(processor.language_model.unk_score_offset						,     3			)




   def 			_lowerCAmelCase		( self     :		Dict			)       ->    Dict:







      """simple docstring"""




      _UpperCAmelCase							:	List[Any]							=   self.get_tokenizer()
      # add token to trigger raise
      tokenizer.add_tokens(["xx"]			)
      with self.assertRaisesRegex(_UpperCamelCase						,     "include"			):
         WavaVecaProcessorWithLM(
             tokenizer=_UpperCamelCase						,     feature_extractor=self.get_feature_extractor()						,     decoder=self.get_decoder()			)




   def 			_lowerCAmelCase		( self     :		str			)       ->    int:







      """simple docstring"""




      _UpperCAmelCase							:	Union[str, Any]							=   self.get_feature_extractor()
      _UpperCAmelCase							:	Any							=   self.get_tokenizer()
      _UpperCAmelCase							:	Optional[Any]							=   self.get_decoder()

      _UpperCAmelCase							:	List[Any]							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      _UpperCAmelCase							:	Tuple							=   floats_list((3, 1_0_0_0)			)

      _UpperCAmelCase							:	List[str]							=   feature_extractor(_UpperCamelCase						,     return_tensors="np"			)
      _UpperCAmelCase							:	Any							=   processor(_UpperCamelCase						,     return_tensors="np"			)

      for key in input_feat_extract.keys():
         self.assertAlmostEqual(input_feat_extract[key].sum()						,     input_processor[key].sum()						,     delta=1e-2			)




   def 			_lowerCAmelCase		( self     :		List[Any]			)       ->    Any:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   self.get_feature_extractor()
      _UpperCAmelCase							:	Optional[int]							=   self.get_tokenizer()
      _UpperCAmelCase							:	List[Any]							=   self.get_decoder()

      _UpperCAmelCase							:	Optional[Any]							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      _UpperCAmelCase							:	List[Any]							=   'This is a test string'

      _UpperCAmelCase							:	str							=   processor(text=_UpperCamelCase			)

      _UpperCAmelCase							:	List[str]							=   tokenizer(_UpperCamelCase			)

      for key in encoded_tok.keys():
         self.assertListEqual(encoded_tok[key]						,     encoded_processor[key]			)




   def 			_lowerCAmelCase		( self     :		Optional[int]						,     lowerCAmelCase__     :		Any=(2, 1_0, 1_6)						,     lowerCAmelCase__     :		int=7_7			)       ->    Optional[Any]:







      """simple docstring"""




      np.random.seed(_UpperCamelCase			)
      return np.random.rand(*_UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		str			)       ->    Dict:







      """simple docstring"""




      _UpperCAmelCase							:	int							=   self.get_feature_extractor()
      _UpperCAmelCase							:	int							=   self.get_tokenizer()
      _UpperCAmelCase							:	Optional[int]							=   self.get_decoder()

      _UpperCAmelCase							:	Union[str, Any]							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      _UpperCAmelCase							:	int							=   self._get_dummy_logits(shape=(1_0, 1_6)						,     seed=1_3			)

      _UpperCAmelCase							:	Union[str, Any]							=   processor.decode(_UpperCamelCase			)

      _UpperCAmelCase							:	List[Any]							=   decoder.decode_beams(_UpperCamelCase			)[0]

      self.assertEqual(decoded_decoder[0]						,     decoded_processor.text			)
      self.assertEqual("</s> <s> </s>"						,     decoded_processor.text			)
      self.assertEqual(decoded_decoder[-2]						,     decoded_processor.logit_score			)
      self.assertEqual(decoded_decoder[-1]						,     decoded_processor.lm_score			)




   @parameterized.expand([[None], ["fork"], ["spawn"]]			)
   def 			_lowerCAmelCase		( self     :		str						,     lowerCAmelCase__     :		Dict			)       ->    str:







      """simple docstring"""




      _UpperCAmelCase							:	List[Any]							=   self.get_feature_extractor()
      _UpperCAmelCase							:	str							=   self.get_tokenizer()
      _UpperCAmelCase							:	Tuple							=   self.get_decoder()

      _UpperCAmelCase							:	Dict							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      _UpperCAmelCase							:	int							=   self._get_dummy_logits()

      # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM.
      #       otherwise, the LM won't be available to the pool's sub-processes.
      # manual logic used to allow parameterized test for both pool=None and pool=Pool(...)
      if pool_context is None:
         _UpperCAmelCase							:	Union[str, Any]							=   processor.batch_decode(_UpperCamelCase			)
      else:
         with get_context(_UpperCamelCase			).Pool() as pool:
            _UpperCAmelCase							:	Union[str, Any]							=   processor.batch_decode(_UpperCamelCase						,     _UpperCamelCase			)

      _UpperCAmelCase							:	List[Any]							=   list(_UpperCamelCase			)

      with get_context("fork"			).Pool() as p:
         _UpperCAmelCase							:	Dict							=   decoder.decode_beams_batch(_UpperCamelCase						,     _UpperCamelCase			)

      _UpperCAmelCase							:	int							=   [], [], []
      for beams in decoded_beams:
         texts_decoder.append(beams[0][0]			)
         logit_scores_decoder.append(beams[0][-2]			)
         lm_scores_decoder.append(beams[0][-1]			)

      self.assertListEqual(_UpperCamelCase						,     decoded_processor.text			)
      self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"]						,     decoded_processor.text			)
      self.assertListEqual(_UpperCamelCase						,     decoded_processor.logit_score			)
      self.assertListEqual(_UpperCamelCase						,     decoded_processor.lm_score			)




   def 			_lowerCAmelCase		( self     :		Union[str, Any]			)       ->    int:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   self.get_feature_extractor()
      _UpperCAmelCase							:	Optional[Any]							=   self.get_tokenizer()
      _UpperCAmelCase							:	Any							=   self.get_decoder()

      _UpperCAmelCase							:	int							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      _UpperCAmelCase							:	Any							=   self._get_dummy_logits()

      _UpperCAmelCase							:	List[str]							=   1_5
      _UpperCAmelCase							:	str							=   -20.0
      _UpperCAmelCase							:	List[Any]							=   -4.0

      _UpperCAmelCase							:	Dict							=   processor.batch_decode(
          _UpperCamelCase						,     beam_width=_UpperCamelCase						,     beam_prune_logp=_UpperCamelCase						,     token_min_logp=_UpperCamelCase						,     )
      _UpperCAmelCase							:	List[str]							=   decoded_processor_out.text

      _UpperCAmelCase							:	Dict							=   list(_UpperCamelCase			)

      with get_context("fork"			).Pool() as pool:
         _UpperCAmelCase							:	Optional[int]							=   decoder.decode_beams_batch(
             _UpperCamelCase						,     _UpperCamelCase						,     beam_width=_UpperCamelCase						,     beam_prune_logp=_UpperCamelCase						,     token_min_logp=_UpperCamelCase						,     )

      _UpperCAmelCase							:	Dict							=   [d[0][0] for d in decoded_decoder_out]
      _UpperCAmelCase							:	Union[str, Any]							=   [d[0][2] for d in decoded_decoder_out]
      _UpperCAmelCase							:	str							=   [d[0][3] for d in decoded_decoder_out]

      self.assertListEqual(_UpperCamelCase						,     _UpperCamelCase			)
      self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"]						,     _UpperCamelCase			)

      self.assertTrue(np.array_equal(_UpperCamelCase						,     decoded_processor_out.logit_score			)			)
      self.assertTrue(np.allclose([-20.054, -18.447]						,     _UpperCamelCase						,     atol=1e-3			)			)

      self.assertTrue(np.array_equal(_UpperCamelCase						,     decoded_processor_out.lm_score			)			)
      self.assertTrue(np.allclose([-15.554, -13.9474]						,     _UpperCamelCase						,     atol=1e-3			)			)




   def 			_lowerCAmelCase		( self     :		List[str]			)       ->    List[Any]:







      """simple docstring"""




      _UpperCAmelCase							:	str							=   self.get_feature_extractor()
      _UpperCAmelCase							:	Tuple							=   self.get_tokenizer()
      _UpperCAmelCase							:	List[str]							=   self.get_decoder()

      _UpperCAmelCase							:	Tuple							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      _UpperCAmelCase							:	Optional[Any]							=   self._get_dummy_logits()

      _UpperCAmelCase							:	List[Any]							=   2.0
      _UpperCAmelCase							:	List[str]							=   5.0
      _UpperCAmelCase							:	Optional[Any]							=   -20.0
      _UpperCAmelCase							:	Union[str, Any]							=   True

      _UpperCAmelCase							:	Any							=   processor.batch_decode(
          _UpperCamelCase						,     alpha=_UpperCamelCase						,     beta=_UpperCamelCase						,     unk_score_offset=_UpperCamelCase						,     lm_score_boundary=_UpperCamelCase						,     )
      _UpperCAmelCase							:	Dict							=   decoded_processor_out.text

      _UpperCAmelCase							:	Any							=   list(_UpperCamelCase			)
      decoder.reset_params(
          alpha=_UpperCamelCase						,     beta=_UpperCamelCase						,     unk_score_offset=_UpperCamelCase						,     lm_score_boundary=_UpperCamelCase						,     )

      with get_context("fork"			).Pool() as pool:
         _UpperCAmelCase							:	Tuple							=   decoder.decode_beams_batch(
             _UpperCamelCase						,     _UpperCamelCase						,     )

      _UpperCAmelCase							:	List[Any]							=   [d[0][0] for d in decoded_decoder_out]

      self.assertListEqual(_UpperCamelCase						,     _UpperCamelCase			)
      self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"]						,     _UpperCamelCase			)
      _UpperCAmelCase							:	int							=   processor.decoder.model_container[processor.decoder._model_key]
      self.assertEqual(lm_model.alpha						,     2.0			)
      self.assertEqual(lm_model.beta						,     5.0			)
      self.assertEqual(lm_model.unk_score_offset						,     -20.0			)
      self.assertEqual(lm_model.score_boundary						,     _UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Tuple			)       ->    Union[str, Any]:







      """simple docstring"""




      _UpperCAmelCase							:	Any							=   WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm"			)

      _UpperCAmelCase							:	Optional[Any]							=   processor.decoder.model_container[processor.decoder._model_key]
      _UpperCAmelCase							:	Union[str, Any]							=   Path(language_model._kenlm_model.path.decode("utf-8"			)			).parent.parent.absolute()

      _UpperCAmelCase							:	List[Any]							=   os.listdir(_UpperCamelCase			)
      _UpperCAmelCase							:	List[str]							=   ['alphabet.json', 'language_model']

      downloaded_decoder_files.sort()
      expected_decoder_files.sort()

      # test that only decoder relevant files from
      # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main
      # are downloaded and none of the rest (e.g. README.md, ...)
      self.assertListEqual(_UpperCamelCase						,     _UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Tuple			)       ->    List[Any]:







      """simple docstring"""




      _UpperCAmelCase							:	List[Any]							=   snapshot_download("hf-internal-testing/processor_with_lm"			)

      _UpperCAmelCase							:	Union[str, Any]							=   WavaVecaProcessorWithLM.from_pretrained(_UpperCamelCase			)

      _UpperCAmelCase							:	Any							=   processor.decoder.model_container[processor.decoder._model_key]
      _UpperCAmelCase							:	Dict							=   Path(language_model._kenlm_model.path.decode("utf-8"			)			).parent.parent.absolute()

      _UpperCAmelCase							:	int							=   os.listdir(_UpperCamelCase			)
      _UpperCAmelCase							:	Dict							=   os.listdir(_UpperCamelCase			)

      local_decoder_files.sort()
      expected_decoder_files.sort()

      # test that both decoder form hub and local files in cache are the same
      self.assertListEqual(_UpperCamelCase						,     _UpperCamelCase			)




   def 			_lowerCAmelCase		( self     :		Any			)       ->    Dict:







      """simple docstring"""




      _UpperCAmelCase							:	Any							=   WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm"			)
      _UpperCAmelCase							:	Any							=   AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm"			)

      _UpperCAmelCase							:	Union[str, Any]							=   floats_list((3, 1_0_0_0)			)

      _UpperCAmelCase							:	Tuple							=   processor_wavaveca(_UpperCamelCase						,     return_tensors="np"			)
      _UpperCAmelCase							:	List[str]							=   processor_auto(_UpperCamelCase						,     return_tensors="np"			)

      for key in input_wavaveca.keys():
         self.assertAlmostEqual(input_wavaveca[key].sum()						,     input_auto[key].sum()						,     delta=1e-2			)

      _UpperCAmelCase							:	Optional[Any]							=   self._get_dummy_logits()

      _UpperCAmelCase							:	List[Any]							=   processor_wavaveca.batch_decode(_UpperCamelCase			)
      _UpperCAmelCase							:	List[str]							=   processor_auto.batch_decode(_UpperCamelCase			)

      self.assertListEqual(decoded_wavaveca.text						,     decoded_auto.text			)




   def 			_lowerCAmelCase		( self     :		Optional[int]			)       ->    int:







      """simple docstring"""




      _UpperCAmelCase							:	str							=   self.get_feature_extractor()
      _UpperCAmelCase							:	Any							=   self.get_tokenizer()
      _UpperCAmelCase							:	List[str]							=   self.get_decoder()

      _UpperCAmelCase							:	Dict							=   WavaVecaProcessorWithLM(tokenizer=_UpperCamelCase						,     feature_extractor=_UpperCamelCase						,     decoder=_UpperCamelCase			)

      self.assertListEqual(
          processor.model_input_names						,     feature_extractor.model_input_names						,     msg="`processor` and `feature_extractor` model input names do not match"						,     )




   @staticmethod
   def 			_lowerCAmelCase		( lowerCAmelCase__     :		List[Any]						,     lowerCAmelCase__     :		int			)       ->    str:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   [d[key] for d in offsets]
      return retrieved_list




   def 			_lowerCAmelCase		( self     :		Dict			)       ->    int:







      """simple docstring"""




      _UpperCAmelCase							:	List[str]							=   WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm"			)
      _UpperCAmelCase							:	Tuple							=   self._get_dummy_logits()[0]

      _UpperCAmelCase							:	Union[str, Any]							=   processor.decode(_UpperCamelCase						,     output_word_offsets=_UpperCamelCase			)
      # check Wav2Vec2CTCTokenizerOutput keys for word
      self.assertEqual(len(outputs.keys()			)						,     4			)
      self.assertTrue("text" in outputs			)
      self.assertTrue("word_offsets" in outputs			)
      self.assertTrue(isinstance(_UpperCamelCase						,     _UpperCamelCase			)			)

      self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"]						,     "word"			)			)						,     outputs.text			)
      self.assertListEqual(self.get_from_offsets(outputs["word_offsets"]						,     "word"			)						,     ["<s>", "<s>", "</s>"]			)
      self.assertListEqual(self.get_from_offsets(outputs["word_offsets"]						,     "start_offset"			)						,     [0, 2, 4]			)
      self.assertListEqual(self.get_from_offsets(outputs["word_offsets"]						,     "end_offset"			)						,     [1, 3, 5]			)




   def 			_lowerCAmelCase		( self     :		Optional[int]			)       ->    Optional[int]:







      """simple docstring"""




      _UpperCAmelCase							:	Union[str, Any]							=   WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm"			)
      _UpperCAmelCase							:	List[Any]							=   self._get_dummy_logits()

      _UpperCAmelCase							:	Any							=   processor.batch_decode(_UpperCamelCase						,     output_word_offsets=_UpperCamelCase			)

      # check Wav2Vec2CTCTokenizerOutput keys for word
      self.assertEqual(len(outputs.keys()			)						,     4			)
      self.assertTrue("text" in outputs			)
      self.assertTrue("word_offsets" in outputs			)
      self.assertTrue(isinstance(_UpperCamelCase						,     _UpperCamelCase			)			)

      self.assertListEqual(
          [" ".join(self.get_from_offsets(_UpperCamelCase						,     "word"			)			) for o in outputs["word_offsets"]]						,     outputs.text			)
      self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0]						,     "word"			)						,     ["<s>", "<s>", "</s>"]			)
      self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0]						,     "start_offset"			)						,     [0, 2, 4]			)
      self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0]						,     "end_offset"			)						,     [1, 3, 5]			)




   @slow
   @require_torch
   @require_torchaudio
   def 			_lowerCAmelCase		( self     :		Optional[Any]			)       ->    List[str]:







      """simple docstring"""




      import torch

      _UpperCAmelCase							:	Optional[Any]							=   load_dataset("common_voice"						,     "en"						,     split="train"						,     streaming=_UpperCamelCase			)
      _UpperCAmelCase							:	Dict							=   ds.cast_column("audio"						,     datasets.Audio(sampling_rate=1_6_0_0_0			)			)
      _UpperCAmelCase							:	Any							=   iter(_UpperCamelCase			)
      _UpperCAmelCase							:	int							=   next(_UpperCamelCase			)

      _UpperCAmelCase							:	List[str]							=   AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm"			)
      _UpperCAmelCase							:	List[Any]							=   WavaVecaForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm"			)

      # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train
      _UpperCAmelCase							:	Dict							=   processor(sample["audio"]["array"]						,     return_tensors="pt"			).input_values

      with torch.no_grad():
         _UpperCAmelCase							:	Optional[int]							=   model(_UpperCamelCase			).logits.cpu().numpy()

      _UpperCAmelCase							:	List[Any]							=   processor.decode(logits[0]						,     output_word_offsets=_UpperCamelCase			)

      _UpperCAmelCase							:	List[str]							=   model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate
      _UpperCAmelCase							:	Tuple							=   [
          {
              'start_time': d['start_offset'] * time_offset,
              'end_time': d['end_offset'] * time_offset,
              'word': d['word'],
          }
          for d in output['word_offsets']
      ]

      _UpperCAmelCase							:	List[str]							=   'WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL'

      # output words
      self.assertEqual(" ".join(self.get_from_offsets(_UpperCamelCase						,     "word"			)			)						,     _UpperCamelCase			)
      self.assertEqual(" ".join(self.get_from_offsets(_UpperCamelCase						,     "word"			)			)						,     output.text			)

      # output times
      _UpperCAmelCase							:	Tuple							=   torch.tensor(self.get_from_offsets(_UpperCamelCase						,     "start_time"			)			)
      _UpperCAmelCase							:	List[Any]							=   torch.tensor(self.get_from_offsets(_UpperCamelCase						,     "end_time"			)			)

      # fmt: off
      _UpperCAmelCase							:	Tuple							=   torch.tensor([1.4199, 1.6599, 2.2599, 3.0, 3.24, 3.5999, 3.7999, 4.0999, 4.26, 4.94, 5.28, 5.6599, 5.78, 5.94, 6.32, 6.5399, 6.6599]			)
      _UpperCAmelCase							:	Optional[int]							=   torch.tensor([1.5399, 1.8999, 2.9, 3.16, 3.5399, 3.72, 4.0199, 4.1799, 4.76, 5.1599, 5.5599, 5.6999, 5.86, 6.1999, 6.38, 6.6199, 6.94]			)
      # fmt: on

      self.assertTrue(torch.allclose(_UpperCamelCase						,     _UpperCamelCase						,     atol=0.01			)			)
      self.assertTrue(torch.allclose(_UpperCamelCase						,     _UpperCamelCase						,     atol=0.01			)			)







import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)




def      lowercase__      (     __snake_case    :							List[Any]     ,       __snake_case    :							List[str]=False  ):


					'''simple docstring'''


					try:
										UpperCAmelCase_    :      int            =						os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										UpperCAmelCase_    :      Optional[int]            =						default
					else:
										# KEY is set, convert it to True or False.
										try:
															UpperCAmelCase_    :      List[Any]            =						strtobool(__snake_case  )
										except ValueError:
															# More values are supported, but let's keep the message simple.
															raise ValueError(F"If set, {key} must be yes or no."  )
					return _value


__UpperCAmelCase								=						parse_flag_from_env('RUN_SLOW', default=False)




def      lowercase__      (     __snake_case    :							int  ):


					'''simple docstring'''


					return unittest.skip('Test was skipped'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Tuple  ):


					'''simple docstring'''


					return unittest.skipUnless(_run_slow_tests     ,       'test is slow'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							List[str]  ):


					'''simple docstring'''


					return unittest.skipUnless(not torch.cuda.is_available()     ,       'test requires only a CPU'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Tuple  ):


					'''simple docstring'''


					return unittest.skipUnless(torch.cuda.is_available()     ,       'test requires a GPU'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							List[str]  ):


					'''simple docstring'''


					return unittest.skipUnless(is_xpu_available()     ,       'test requires a XPU'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							str  ):


					'''simple docstring'''


					return unittest.skipUnless(is_mps_available()     ,       'test requires a `mps` backend support in `torch`'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Tuple  ):


					'''simple docstring'''


					return unittest.skipUnless(
					    is_transformers_available() and is_datasets_available()     ,       'test requires the Hugging Face suite'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							str  ):


					'''simple docstring'''


					return unittest.skipUnless(is_bnb_available()     ,       'test requires the bitsandbytes library'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Dict  ):


					'''simple docstring'''


					return unittest.skipUnless(is_tpu_available()     ,       'test requires TPU'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Tuple  ):


					'''simple docstring'''


					return unittest.skipUnless(torch.cuda.device_count() == 1     ,       'test requires a GPU'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Dict  ):


					'''simple docstring'''


					return unittest.skipUnless(torch.xpu.device_count() == 1     ,       'test requires a XPU'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Optional[int]  ):


					'''simple docstring'''


					return unittest.skipUnless(torch.cuda.device_count() > 1     ,       'test requires multiple GPUs'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							int  ):


					'''simple docstring'''


					return unittest.skipUnless(torch.xpu.device_count() > 1     ,       'test requires multiple XPUs'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Dict  ):


					'''simple docstring'''


					return unittest.skipUnless(is_safetensors_available()     ,       'test requires safetensors'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Tuple  ):


					'''simple docstring'''


					return unittest.skipUnless(is_deepspeed_available()     ,       'test requires DeepSpeed'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							List[Any]  ):


					'''simple docstring'''


					return unittest.skipUnless(is_torch_version('>='     ,       '1.12.0'  )     ,       'test requires torch version >= 1.12.0'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							Dict=None     ,       __snake_case    :							Dict=None  ):


					'''simple docstring'''


					if test_case is None:
										return partial(__snake_case     ,       version=__snake_case  )
					return unittest.skipUnless(is_torch_version('>='     ,       __snake_case  )     ,       F"test requires torch version >= {version}"  )(__snake_case  )




def      lowercase__      (     __snake_case    :							str  ):


					'''simple docstring'''


					return unittest.skipUnless(is_tensorboard_available()     ,       'test requires Tensorboard'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							List[str]  ):


					'''simple docstring'''


					return unittest.skipUnless(is_wandb_available()     ,       'test requires wandb'  )(__snake_case  )




def      lowercase__      (     __snake_case    :							str  ):


					'''simple docstring'''


					return unittest.skipUnless(is_comet_ml_available()     ,       'test requires comet_ml'  )(__snake_case  )


__UpperCAmelCase								=						(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)




def      lowercase__      (     __snake_case    :							List[Any]  ):


					'''simple docstring'''


					return unittest.skipUnless(
					    _atleast_one_tracker_available     ,       'test requires at least one tracker to be available and for `comet_ml` to not be installed'     ,       )(__snake_case  )



class   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    Union[str, Any]       						=  True



		@classmethod
		def 					__UpperCAmelCase			(							cls   )	->							Union[str, Any]:
							UpperCAmelCase_    :      List[Any]            =						tempfile.mkdtemp()



		@classmethod
		def 					__UpperCAmelCase			(							cls   )	->							List[str]:
							if os.path.exists(cls.tmpdir   ):
												shutil.rmtree(cls.tmpdir   )



		def 					__UpperCAmelCase			(							self   )	->							str:
							if self.clear_on_setup:
												for path in Path(self.tmpdir   ).glob('**/*'   ):
																	if path.is_file():
																						path.unlink()
																	elif path.is_dir():
																						shutil.rmtree(_UpperCamelCase   )





class   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							super().tearDown()
							# Reset the state of the AcceleratorState singleton.
							AcceleratorState._reset_state()
							PartialState._reset_state()





class   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase   )	->							Any:
							UpperCAmelCase_    :      List[Any]            =						mocks if isinstance(_UpperCamelCase				,		(tuple, list)   ) else [mocks]
							for m in self.mocks:
												m.start()
												self.addCleanup(m.stop   )





def      lowercase__      (     __snake_case    :							int  ):


					'''simple docstring'''


					UpperCAmelCase_    :      int            =						AcceleratorState()
					UpperCAmelCase_    :      str            =						tensor[None].clone().to(state.device  )
					UpperCAmelCase_    :      List[str]            =						gather(__snake_case  ).cpu()
					UpperCAmelCase_    :      List[Any]            =						tensor[0].cpu()
					for i in range(tensors.shape[0]  ):
										if not torch.equal(tensors[i]     ,       __snake_case  ):
															return False
					return True



class   lowerCamelCase      :







		'''simple docstring'''



		def __init__(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )	->							Any:
							UpperCAmelCase_    :      str            =						returncode
							UpperCAmelCase_    :      Optional[Any]            =						stdout
							UpperCAmelCase_    :      Optional[Any]            =						stderr





async def      lowercase__      (     __snake_case    :							Optional[Any]     ,       __snake_case    :							Optional[int]  ):


					'''simple docstring'''


					while True:
										UpperCAmelCase_    :      Dict            =						await stream.readline()
										if line:
															callback(__snake_case  )
										else:
															break




async def      lowercase__      (     __snake_case    :							Optional[int]     ,       __snake_case    :							Dict=None     ,       __snake_case    :							str=None     ,       __snake_case    :							Dict=None     ,       __snake_case    :							List[str]=False     ,       __snake_case    :							Optional[int]=False  ):


					'''simple docstring'''


					if echo:
										print('\nRunning: '     ,       ' '.join(__snake_case  )  )

					UpperCAmelCase_    :      Optional[Any]            =						await asyncio.create_subprocess_exec(
					    cmd[0]     ,       *cmd[1:]     ,       stdin=__snake_case     ,       stdout=asyncio.subprocess.PIPE     ,       stderr=asyncio.subprocess.PIPE     ,       env=__snake_case     ,       )

					# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
					# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
					#
					# If it starts hanging, will need to switch to the following code. The problem is that no data
					# will be seen until it's done and if it hangs for example there will be no debug info.
					# out, err = await p.communicate()
					# return _RunOutput(p.returncode, out, err)

					UpperCAmelCase_    :      Any            =						[]
					UpperCAmelCase_    :      str            =						[]

					def tee(__snake_case    :							Dict     ,       __snake_case    :							Union[str, Any]     ,       __snake_case    :							Tuple     ,       __snake_case    :							Optional[int]=""  ):
										UpperCAmelCase_    :      List[str]            =						line.decode('utf-8'  ).rstrip()
										sink.append(__snake_case  )
										if not quiet:
															print(__snake_case     ,       __snake_case     ,       file=__snake_case  )

    # XXX: the timeout doesn't seem to make any difference here
					await asyncio.wait(
					    [
					        asyncio.create_task(_read_stream(p.stdout     ,       lambda __snake_case  : tee(__snake_case     ,       __snake_case     ,       sys.stdout     ,       label='stdout:'  )  )  ),
					        asyncio.create_task(_read_stream(p.stderr     ,       lambda __snake_case  : tee(__snake_case     ,       __snake_case     ,       sys.stderr     ,       label='stderr:'  )  )  ),
					    ]     ,       timeout=__snake_case     ,       )
					return _RunOutput(await p.wait()     ,       __snake_case     ,       __snake_case  )




def      lowercase__      (     __snake_case    :							Optional[Any]     ,       __snake_case    :							List[Any]=None     ,       __snake_case    :							str=None     ,       __snake_case    :							Tuple=180     ,       __snake_case    :							Dict=False     ,       __snake_case    :							Optional[Any]=True  ):


					'''simple docstring'''


					UpperCAmelCase_    :      str            =						asyncio.get_event_loop()
					UpperCAmelCase_    :      int            =						loop.run_until_complete(
					    _stream_subprocess(__snake_case     ,       env=__snake_case     ,       stdin=__snake_case     ,       timeout=__snake_case     ,       quiet=__snake_case     ,       echo=__snake_case  )  )

					UpperCAmelCase_    :      int            =						' '.join(__snake_case  )
					if result.returncode > 0:
										UpperCAmelCase_    :      int            =						'\n'.join(result.stderr  )
										raise RuntimeError(
										    F"'{cmd_str}' failed with returncode {result.returncode}\n\n"
										    F"The combined stderr from workers follows:\n{stderr}"  )

					return result



class   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		pass





def      lowercase__      (     __snake_case    :							List[str]     ,       __snake_case    :							List[Any]=False  ):


					'''simple docstring'''


					try:
										UpperCAmelCase_    :      List[Any]            =						subprocess.check_output(__snake_case     ,       stderr=subprocess.STDOUT  )
										if return_stdout:
															if hasattr(__snake_case     ,       'decode'  ):
																				UpperCAmelCase_    :      str            =						output.decode('utf-8'  )
															return output
					except subprocess.CalledProcessError as e:
										raise SubprocessCallException(
										    F"Command `{' '.join(__snake_case  )}` failed with the following error:\n\n{e.output.decode()}"  ) from e






