codingutf8 20212023 huggingface inc licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license tests for the encodec feature extractor import itertools import random import unittest import numpy as np from transformers import encodecfeatureextractor from transformers testingutils import requiretorch from transformers utils importutils import istorchavailable from testsequencefeatureextractioncommon import sequencefeatureextractiontestmixin if istorchavailable import torch globalrng random random copied from tests models whisper testfeatureextractionwhisper floatslist def floatslistshape scale1 0 rngnone namenone make sure that inputs increase in size tests that all call wrap to encodeplus and batchencodeplus create three inputs of length 800 1000 and 1200 test not batched input test batched automatic decoding with librispeech fmt off fmt on fmt off fmt on would be easier if the stride was like pad and trunc raise an error truncate to chunk force truncate to maxlength pad to chunk pad to chunk force pad to max length force no pad no pad if no chunklengths no pad if no overlap coding utf 8 2021 2023 huggingface inc licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license tests for the encodec feature extractor copied from tests models whisper test_feature_extraction_whisper floats_list creates a random float32 tensor make sure that inputs increase in size tests that all call wrap to encode_plus and batch_encode_plus create three inputs of length 800 1000 and 1200 test not batched input test batched automatic decoding with librispeech fmt off fmt on fmt off fmt on would be easier if the stride was like pad and trunc raise an error truncate to chunk 2 chunks force truncate to max_length pad to chunk pad to chunk force pad to max length force no pad no pad if no chunk_length_s no pad if no overlap
import itertools
import random
import unittest

import numpy as np

from transformers import EncodecFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
    import torch


global_rng = random.Random()



def floats_list(shape, scale=1.0, rng=None, name=None):
    
    if rng is None:
        rng = global_rng

    values = []
    for batch_idx in range(shape[0]):
        values.append([])
        for _ in range(shape[1]):
            values[-1].append(rng.random() * scale)

    return values


@require_torch
class EnCodecFeatureExtractionTester(unittest.TestCase):
    def __init__(
        self,
        parent,
        batch_size=7,
        min_seq_length=400,
        max_seq_length=2000,
        feature_size=1,
        padding_value=0.0,
        sampling_rate=24000,
        return_attention_mask=True,
    ):
        self.parent = parent
        self.batch_size = batch_size
        self.min_seq_length = min_seq_length
        self.max_seq_length = max_seq_length
        self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
        self.feature_size = feature_size
        self.padding_value = padding_value
        self.sampling_rate = sampling_rate
        self.return_attention_mask = return_attention_mask

    def prepare_feat_extract_dict(self):
        return {
            "feature_size": self.feature_size,
            "padding_value": self.padding_value,
            "sampling_rate": self.sampling_rate,
            "return_attention_mask": self.return_attention_mask,
        }

    def prepare_inputs_for_common(self, equal_length=False, numpify=False):
        def _flatten(list_of_lists):
            return list(itertools.chain(*list_of_lists))

        if equal_length:
            audio_inputs = floats_list((self.batch_size, self.max_seq_length))
        else:
            
            audio_inputs = [
                _flatten(floats_list((x, self.feature_size)))
                for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff)
            ]

        if numpify:
            audio_inputs = [np.asarray(x) for x in audio_inputs]

        return audio_inputs


@require_torch
class EnCodecFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):
    feature_extraction_class = EncodecFeatureExtractor

    def setUp(self):
        self.feat_extract_tester = EnCodecFeatureExtractionTester(self)

    def test_call(self):
        
        feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        
        audio_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
        np_audio_inputs = [np.asarray(audio_input) for audio_input in audio_inputs]

        
        encoded_sequences_1 = feat_extract(audio_inputs[0], return_tensors="np").input_values
        encoded_sequences_2 = feat_extract(np_audio_inputs[0], return_tensors="np").input_values
        self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3))

        
        encoded_sequences_1 = feat_extract(audio_inputs, padding=True, return_tensors="np").input_values
        encoded_sequences_2 = feat_extract(np_audio_inputs, padding=True, return_tensors="np").input_values
        for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):
            self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))

    def test_double_precision_pad(self):
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        np_audio_inputs = np.random.rand(100).astype(np.float64)
        py_audio_inputs = np_audio_inputs.tolist()

        for inputs in [py_audio_inputs, np_audio_inputs]:
            np_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="np")
            self.assertTrue(np_processed.input_values.dtype == np.float32)
            pt_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="pt")
            self.assertTrue(pt_processed.input_values.dtype == torch.float32)

    def _load_datasamples(self, num_samples):
        from datasets import load_dataset

        ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        
        audio_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"]

        return [x["array"] for x in audio_samples]

    def test_integration(self):
        
        EXPECTED_INPUT_VALUES = torch.tensor(
            [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03,
             3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03,
             2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04,
             4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03,
             7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04,
             4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03]
        )
        
        input_audio = self._load_datasamples(1)
        feature_extractor = EncodecFeatureExtractor()
        input_values = feature_extractor(input_audio, return_tensors="pt").input_values
        self.assertEquals(input_values.shape, (1, 1, 93680))
        self.assertTrue(torch.allclose(input_values[0, 0, :30], EXPECTED_INPUT_VALUES, atol=1e-6))

    def test_integration_stereo(self):
        
        EXPECTED_INPUT_VALUES = torch.tensor(
            [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03,
             3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03,
             2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04,
             4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03,
             7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04,
             4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03]
        )
        
        input_audio = self._load_datasamples(1)
        input_audio = [np.tile(input_audio[0][None], reps=(2, 1))]
        input_audio[0][1] *= 0.5
        feature_extractor = EncodecFeatureExtractor(feature_size=2)
        input_values = feature_extractor(input_audio, return_tensors="pt").input_values
        self.assertEquals(input_values.shape, (1, 2, 93680))
        self.assertTrue(torch.allclose(input_values[0, 0, :30], EXPECTED_INPUT_VALUES, atol=1e-6))
        self.assertTrue(torch.allclose(input_values[0, 1, :30], EXPECTED_INPUT_VALUES * 0.5, atol=1e-6))

    def test_truncation_and_padding(self):
        input_audio = self._load_datasamples(2)
        
        feature_extractor = EncodecFeatureExtractor(feature_size=1, chunk_length_s=1, overlap=0.01)

        
        with self.assertRaisesRegex(
            ValueError,
            "^Both padding and truncation were set. Make sure you only set one.$",
        ):
            truncated_outputs = feature_extractor(
                input_audio, padding="max_length", truncation=True, return_tensors="pt"
            ).input_values

        
        truncated_outputs = feature_extractor(input_audio, truncation=True, return_tensors="pt").input_values
        self.assertEquals(truncated_outputs.shape, (2, 1, 71520))  

        
        truncated_outputs = feature_extractor(
            input_audio, truncation=True, max_length=48000, return_tensors="pt"
        ).input_values
        self.assertEquals(truncated_outputs.shape, (2, 1, 48000))

        
        padded_outputs = feature_extractor(input_audio, padding=True, return_tensors="pt").input_values
        self.assertEquals(padded_outputs.shape, (2, 1, 95280))

        
        truncated_outputs = feature_extractor(input_audio, return_tensors="pt").input_values
        self.assertEquals(truncated_outputs.shape, (2, 1, 95280))

        
        truncated_outputs = feature_extractor(
            input_audio, padding="max_length", max_length=100000, return_tensors="pt"
        ).input_values
        self.assertEquals(truncated_outputs.shape, (2, 1, 100000))

        
        with self.assertRaisesRegex(
            ValueError,
            "^Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.$",
        ):
            truncated_outputs = feature_extractor(input_audio, padding=False, return_tensors="pt").input_values

        truncated_outputs = feature_extractor(input_audio[0], padding=False, return_tensors="pt").input_values
        self.assertEquals(truncated_outputs.shape, (1, 1, 93680))

        
        feature_extractor.chunk_length_s = None
        with self.assertRaisesRegex(
            ValueError,
            "^Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.$",
        ):
            truncated_outputs = feature_extractor(input_audio, padding=False, return_tensors="pt").input_values

        truncated_outputs = feature_extractor(input_audio[0], padding=False, return_tensors="pt").input_values
        self.assertEquals(truncated_outputs.shape, (1, 1, 93680))

        
        feature_extractor.chunk_length_s = 2
        feature_extractor.overlap = None
        with self.assertRaisesRegex(
            ValueError,
            "^Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.$",
        ):
            truncated_outputs = feature_extractor(input_audio, padding=False, return_tensors="pt").input_values

        truncated_outputs = feature_extractor(input_audio[0], padding=False, return_tensors="pt").input_values
        self.assertEquals(truncated_outputs.shape, (1, 1, 93680))