






'''simple docstring'''





import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Value
from datasets.packaged_modules.json.json import Json



@pytest.fixture
def 			__UpperCAmelCase				(lowercase__				)		->				List[Any]:

						'''simple docstring'''


						a_				     =   tmp_path / "file.jsonl"
						a_				     =   textwrap.dedent(
						    "\\n        {\"col_1\": -1}\n        {\"col_1\": 1, \"col_2\": 2}\n        {\"col_1\": 10, \"col_2\": 20}\n        "				)
						with open(lowercase__	,"w"				) as f:
												f.write(lowercase__				)
						return str(lowercase__				)



@pytest.fixture
def 			__UpperCAmelCase				(lowercase__				)		->				str:

						'''simple docstring'''


						a_				     =   tmp_path / "file_utf16_encoded.jsonl"
						a_				     =   textwrap.dedent(
						    "\\n        {\"col_1\": -1}\n        {\"col_1\": 1, \"col_2\": 2}\n        {\"col_1\": 10, \"col_2\": 20}\n        "				)
						with open(lowercase__	,"w"	,encoding="utf-16"				) as f:
												f.write(lowercase__				)
						return str(lowercase__				)



@pytest.fixture
def 			__UpperCAmelCase				(lowercase__				)		->				Dict:

						'''simple docstring'''


						a_				     =   tmp_path / "file_with_list_of_dicts.json"
						a_				     =   textwrap.dedent(
						    "\\n        [\n            {\"col_1\": -1},\n            {\"col_1\": 1, \"col_2\": 2},\n            {\"col_1\": 10, \"col_2\": 20}\n        ]\n        "				)
						with open(lowercase__	,"w"				) as f:
												f.write(lowercase__				)
						return str(lowercase__				)



@pytest.fixture
def 			__UpperCAmelCase				(lowercase__				)		->				Dict:

						'''simple docstring'''


						a_				     =   tmp_path / "file_with_list_of_dicts_field.json"
						a_				     =   textwrap.dedent(
						    "\\n        {\n            \"field1\": 1,\n            \"field2\": \"aabb\",\n            \"field3\": [\n                {\"col_1\": -1},\n                {\"col_1\": 1, \"col_2\": 2},\n                {\"col_1\": 10, \"col_2\": 20}\n            ]\n        }\n        "				)
						with open(lowercase__	,"w"				) as f:
												f.write(lowercase__				)
						return str(lowercase__				)



@pytest.mark.parametrize(
    "file_fixture, config_kwargs"	,[
        ("jsonl_file", {}),
        ("jsonl_file_utf16_encoded", {"encoding": "utf-16"}),
        ("json_file_with_list_of_dicts", {}),
        ("json_file_with_list_of_dicts_field", {"field": "field3"}),
    ]	,)
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				List[str]:

						'''simple docstring'''


						a_				     =   Json(**lowercase__				)
						a_				     =   json._generate_tables([[request.getfixturevalue(lowercase__				)]]				)
						a_				     =   pa.concat_tables([table for _, table in generator]				)
						assert pa_table.to_pydict() == {"col_1": [-1, 1, 10], "col_2": [None, 2, 20]}



@pytest.mark.parametrize(
    "file_fixture, config_kwargs"	,[
        (
            "jsonl_file",
            {"features": Features({"col_1": Value("int64"				), "col_2": Value("int64"				), "missing_col": Value("string"				)}				)},
        ),
        (
            "json_file_with_list_of_dicts",
            {"features": Features({"col_1": Value("int64"				), "col_2": Value("int64"				), "missing_col": Value("string"				)}				)},
        ),
        (
            "json_file_with_list_of_dicts_field",
            {
                "field": "field3",
                "features": Features(
                    {"col_1": Value("int64"				), "col_2": Value("int64"				), "missing_col": Value("string"				)}				),
            },
        ),
    ]	,)
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				int:

						'''simple docstring'''


						a_				     =   Json(**lowercase__				)
						a_				     =   json._generate_tables([[request.getfixturevalue(lowercase__				)]]				)
						a_				     =   pa.concat_tables([table for _, table in generator]				)
						assert pa_table.to_pydict() == {"col_1": [-1, 1, 10], "col_2": [None, 2, 20], "missing_col": [None, None, None]}











'''simple docstring'''





import json
import os
import shutil
import tempfile
import unittest

from transformers import is_speech_available, is_torch_available
from transformers.models.speechta import SpeechTaTokenizer
from transformers.testing_utils import get_tests_dir, require_torch
from transformers.utils import FEATURE_EXTRACTOR_NAME


if is_speech_available() and is_torch_available():
							from transformers import SpeechTaFeatureExtractor, SpeechTaProcessor

							from .test_feature_extraction_speechta import floats_list


a_      = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model')





@require_torch
class 		SCREAMING_SNAKE_CASE__   (     unittest.TestCase    ):



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






								'''simple docstring'''


								a_				     =   tempfile.mkdtemp()

								a_				     =   SpeechTaTokenizer(a)
								tokenizer.save_pretrained(self.tmpdirname)

								a_				     =   {
								    "feature_size": 1,
								    "padding_value": 0.0,
								    "sampling_rate": 1_60_00,
								    "do_normalize": False,
								    "num_mel_bins": 80,
								    "hop_length": 16,
								    "win_length": 64,
								    "win_function": "hann_window",
								    "fmin": 80,
								    "fmax": 76_00,
								    "mel_floor": 1e-10,
								    "reduction_factor": 2,
								    "return_attention_mask": True,
								}

								a_				     =   os.path.join(self.tmpdirname				,   a)
								with open(self.feature_extraction_file				,   "w"				,   encoding="utf-8") as fp:
														fp.write(json.dumps(a) + "\n")



		def _lowerCAmelCase     (    self:    Any				,   **a:    List[Any])  ->Optional[Any]:






								'''simple docstring'''


								return SpeechTaTokenizer.from_pretrained(self.tmpdirname				,   **a)



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






								'''simple docstring'''


								return SpeechTaFeatureExtractor.from_pretrained(self.tmpdirname				,   **a)



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






								'''simple docstring'''


								shutil.rmtree(self.tmpdirname)



		def _lowerCAmelCase     (    self:    Any)  ->str:






								'''simple docstring'''


								a_				     =   self.get_tokenizer()
								a_				     =   self.get_feature_extractor()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

								processor.save_pretrained(self.tmpdirname)
								a_				     =   SpeechTaProcessor.from_pretrained(self.tmpdirname)

								self.assertEqual(processor.tokenizer.get_vocab()				,   tokenizer.get_vocab())
								self.assertIsInstance(processor.tokenizer				,   a)

								self.assertEqual(processor.feature_extractor.to_json_string()				,   feature_extractor.to_json_string())
								self.assertIsInstance(processor.feature_extractor				,   a)



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






								'''simple docstring'''


								a_				     =   SpeechTaProcessor(tokenizer=self.get_tokenizer()				,   feature_extractor=self.get_feature_extractor())
								processor.save_pretrained(self.tmpdirname)

								a_				     =   self.get_tokenizer(bos_token="(BOS)"				,   eos_token="(EOS)")
								a_				     =   self.get_feature_extractor(do_normalize=a				,   padding_value=1.0)

								a_				     =   SpeechTaProcessor.from_pretrained(
								    self.tmpdirname				,   bos_token="(BOS)"				,   eos_token="(EOS)"				,   do_normalize=a				,   padding_value=1.0)

								self.assertEqual(processor.tokenizer.get_vocab()				,   tokenizer_add_kwargs.get_vocab())
								self.assertIsInstance(processor.tokenizer				,   a)

								self.assertEqual(processor.feature_extractor.to_json_string()				,   feature_extractor_add_kwargs.to_json_string())
								self.assertIsInstance(processor.feature_extractor				,   a)



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






								'''simple docstring'''


								a_				     =   self.get_feature_extractor()
								a_				     =   self.get_tokenizer()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

								a_				     =   floats_list((3, 10_00))

								a_				     =   feature_extractor(audio=a				,   return_tensors="np")
								a_				     =   processor(audio=a				,   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:    Tuple)  ->Union[str, Any]:






								'''simple docstring'''


								a_				     =   self.get_feature_extractor()
								a_				     =   self.get_tokenizer()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

								a_				     =   floats_list((3, 10_00))

								a_				     =   feature_extractor(audio_target=a				,   return_tensors="np")
								a_				     =   processor(audio_target=a				,   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:    str)  ->Dict:






								'''simple docstring'''


								a_				     =   self.get_feature_extractor()
								a_				     =   self.get_tokenizer()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

								a_				     =   "This is a test string"

								a_				     =   processor(text=a)
								a_				     =   tokenizer(a)

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



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






								'''simple docstring'''


								a_				     =   self.get_feature_extractor()
								a_				     =   self.get_tokenizer()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

								a_				     =   "This is a test string"

								a_				     =   processor(text_target=a)
								a_				     =   tokenizer(a)

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



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






								'''simple docstring'''


								a_				     =   self.get_feature_extractor()
								a_				     =   self.get_tokenizer()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

								a_				     =   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

								a_				     =   processor.batch_decode(a)
								a_				     =   tokenizer.batch_decode(a)

								self.assertListEqual(a				,   a)




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






								'''simple docstring'''


								a_				     =   self.get_feature_extractor()
								a_				     =   self.get_tokenizer()

								a_				     =   SpeechTaProcessor(tokenizer=a				,   feature_extractor=a)

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



