codingutf8 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 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 copied from tests models whisper testfeatureextractionwhisper floatslist creates a random float32 tensor if rng is none rng globalrng values for batchidx in rangeshape0 values append for in rangeshape1 values1 appendrng random scale return values requiretorch class seamlessm4tfeatureextractiontesterunittest testcase def init self parent batchsize7 minseqlength400 maxseqlength2000 featuresize10 paddingvalue0 0 samplingrate4000 returnattentionmasktrue donormalizetrue stride2 self parent parent self batchsize batchsize self minseqlength minseqlength self maxseqlength maxseqlength self seqlengthdiff self maxseqlength self minseqlength self batchsize 1 self paddingvalue paddingvalue self samplingrate samplingrate self returnattentionmask returnattentionmask self donormalize donormalize self featuresize featuresize self stride stride self nummelbins featuresize def preparefeatextractdictself return featuresize self featuresize nummelbins self nummelbins paddingvalue self paddingvalue samplingrate self samplingrate stride self stride returnattentionmask self returnattentionmask donormalize self donormalize copied from tests models whisper testfeatureextractionwhisper whisperfeatureextractiontester prepareinputsforcommon def prepareinputsforcommonself equallengthfalse numpifyfalse def flattenlistoflists return listitertools chainlistoflists if equallength speechinputs floatslistself maxseqlength self featuresize for in rangeself batchsize else make sure that inputs increase in size speechinputs floatslistx self featuresize for x in rangeself minseqlength self maxseqlength self seqlengthdiff if numpify speechinputs np asarrayx for x in speechinputs return speechinputs requiretorch class seamlessm4tfeatureextractiontestsequencefeatureextractiontestmixin unittest testcase featureextractionclass seamlessm4tfeatureextractor if isspeechavailable else none def setupself self featextracttester seamlessm4tfeatureextractiontesterself def testfeatextractfromandsavepretrainedself featextractfirst self featureextractionclassself featextractdict with tempfile temporarydirectory as tmpdirname savedfile featextractfirst savepretrainedtmpdirname0 checkjsonfilehascorrectformatsavedfile featextractsecond self featureextractionclass frompretrainedtmpdirname dictfirst featextractfirst todict dictsecond featextractsecond todict self assertdictequaldictfirst dictsecond def testfeatextracttojsonfileself featextractfirst self featureextractionclassself featextractdict with tempfile temporarydirectory as tmpdirname jsonfilepath os path jointmpdirname featextract json featextractfirst tojsonfilejsonfilepath featextractsecond self featureextractionclass fromjsonfilejsonfilepath dictfirst featextractfirst todict dictsecond featextractsecond todict self assertequaldictfirst dictsecond def testcallself tests that all call wrap to encodeplus and batchencodeplus featureextractor self featureextractionclassself featextracttester preparefeatextractdict create three inputs of length 800 1000 and 1200 speechinputs floatslist1 x0 for x in range800 1400 200 npspeechinputs np asarrayspeechinput for speechinput in speechinputs test feature size inputfeatures featureextractornpspeechinputs paddingtrue returntensorsnp inputfeatures self asserttrueinputfeatures ndim 3 self asserttrueinputfeatures shape0 3 self asserttrueinputfeatures shape1 featureextractor featuresize featureextractor stride test not batched input encodedsequences1 featureextractorspeechinputs0 returntensorsnp inputfeatures encodedsequences2 featureextractornpspeechinputs0 returntensorsnp inputfeatures self asserttruenp allcloseencodedsequences1 encodedsequences2 atol1e3 test batched encodedsequences1 featureextractorspeechinputs returntensorsnp inputfeatures encodedsequences2 featureextractornpspeechinputs returntensorsnp inputfeatures for encseq1 encseq2 in zipencodedsequences1 encodedsequences2 self asserttruenp allcloseencseq1 encseq2 atol1e3 test 2d numpy arrays are batched speechinputs floatslist1 x0 for x in 800 800 800 npspeechinputs np asarrayspeechinputs encodedsequences1 featureextractorspeechinputs returntensorsnp inputfeatures encodedsequences2 featureextractornpspeechinputs returntensorsnp inputfeatures for encseq1 encseq2 in zipencodedsequences1 encodedsequences2 self asserttruenp allcloseencseq1 encseq2 atol1e3 requiretorch copied from tests models whisper testfeatureextractionwhisper whisperfeatureextractiontest testdoubleprecisionpad def testdoubleprecisionpadself import torch featureextractor self featureextractionclassself featextracttester preparefeatextractdict npspeechinputs np random rand100 32 astypenp float64 pyspeechinputs npspeechinputs tolist for inputs in pyspeechinputs npspeechinputs npprocessed featureextractor padinputfeatures inputs returntensorsnp self asserttruenpprocessed inputfeatures dtype np float32 ptprocessed featureextractor padinputfeatures inputs returntensorspt self asserttrueptprocessed inputfeatures dtype torch float32 def loaddatasampleself id ds loaddatasethfinternaltestinglibrispeechasrdummy clean splitvalidation automatic decoding with librispeech speechsample ds sortididaudioarray return torch fromnumpyspeechsample unsqueeze0 def testintegrationself fmt off expectedinputfeatures torch tensor 1 5621 1 4236 1 3335 1 3991 1 2881 1 1133 0 9710 0 8895 0 8280 0 7376 0 7194 0 6896 0 6849 0 6788 0 6545 0 6610 0 6566 0 5738 0 5252 0 5533 0 5887 0 6116 0 5971 0 4956 0 2881 0 1512 0 0299 0 1762 0 2728 0 2236 fmt on inputspeech self loaddatasample10 featureextractor seamlessm4tfeatureextractor inputfeatures featureextractorinputspeech returntensorspt inputfeatures featureextractorinputspeech returntensorspt inputfeatures0 5 30 self assertequalinputfeatures shape 1 279 160 self asserttruetorch allcloseinputfeatures0 5 30 expectedinputfeatures atol1e4 def testzeromeanunitvariancenormalizationtruncnplongestself featextract self featureextractionclassself featextracttester preparefeatextractdict audio self loaddatasample1 audio audio audio min audio max audio min 65535 rescale to 0 65535 to show issue audio featextract zeromeanunitvarnormaudio attentionmasknone0 self asserttrueaudio mean 1e3 all self asserttrueaudio var 1 abs 1e3 all coding utf 8 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 copied from tests models whisper test_feature_extraction_whisper floats_list creates a random float32 tensor copied from tests models whisper test_feature_extraction_whisper whisperfeatureextractiontester prepare_inputs_for_common 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 feature size test not batched input test batched test 2 d numpy arrays are batched copied from tests models whisper test_feature_extraction_whisper whisperfeatureextractiontest test_double_precision_pad automatic decoding with librispeech fmt off fmt on rescale to 0 65535 to show issue
import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import SeamlessM4TFeatureExtractor, is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, 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 SeamlessM4TFeatureExtractionTester(unittest.TestCase):
    def __init__(
        self,
        parent,
        batch_size=7,
        min_seq_length=400,
        max_seq_length=2000,
        feature_size=10,
        padding_value=0.0,
        sampling_rate=4_000,
        return_attention_mask=True,
        do_normalize=True,
        stride=2,
    ):
        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.padding_value = padding_value
        self.sampling_rate = sampling_rate
        self.return_attention_mask = return_attention_mask
        self.do_normalize = do_normalize
        self.feature_size = feature_size
        self.stride = stride
        self.num_mel_bins = feature_size

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

    
    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:
            speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
        else:
            
            speech_inputs = [
                floats_list((x, self.feature_size))
                for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff)
            ]
        if numpify:
            speech_inputs = [np.asarray(x) for x in speech_inputs]
        return speech_inputs


@require_torch
class SeamlessM4TFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):
    feature_extraction_class = SeamlessM4TFeatureExtractor if is_speech_available() else None

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

    def test_feat_extract_from_and_save_pretrained(self):
        feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)

        with tempfile.TemporaryDirectory() as tmpdirname:
            saved_file = feat_extract_first.save_pretrained(tmpdirname)[0]
            check_json_file_has_correct_format(saved_file)
            feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname)

        dict_first = feat_extract_first.to_dict()
        dict_second = feat_extract_second.to_dict()
        self.assertDictEqual(dict_first, dict_second)

    def test_feat_extract_to_json_file(self):
        feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)

        with tempfile.TemporaryDirectory() as tmpdirname:
            json_file_path = os.path.join(tmpdirname, "feat_extract.json")
            feat_extract_first.to_json_file(json_file_path)
            feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path)

        dict_first = feat_extract_first.to_dict()
        dict_second = feat_extract_second.to_dict()
        self.assertEqual(dict_first, dict_second)

    def test_call(self):
        
        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        
        speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
        np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs]

        
        input_features = feature_extractor(np_speech_inputs, padding=True, return_tensors="np").input_features
        self.assertTrue(input_features.ndim == 3)
        self.assertTrue(input_features.shape[0] == 3)
        self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size * feature_extractor.stride)

        
        encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features
        encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features
        self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3))

        
        encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features
        encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features
        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))

        
        speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)]
        np_speech_inputs = np.asarray(speech_inputs)
        encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features
        encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features
        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))

    @require_torch
    
    def test_double_precision_pad(self):
        import torch

        feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        np_speech_inputs = np.random.rand(100, 32).astype(np.float64)
        py_speech_inputs = np_speech_inputs.tolist()

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

    def _load_datasample(self, id):
        ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        
        speech_sample = ds.sort("id")[id]["audio"]["array"]

        return torch.from_numpy(speech_sample).unsqueeze(0)

    def test_integration(self):
        
        EXPECTED_INPUT_FEATURES = torch.tensor(
            [
            -1.5621, -1.4236, -1.3335, -1.3991, -1.2881, -1.1133, -0.9710, -0.8895,
            -0.8280, -0.7376, -0.7194, -0.6896, -0.6849, -0.6788, -0.6545, -0.6610,
            -0.6566, -0.5738, -0.5252, -0.5533, -0.5887, -0.6116, -0.5971, -0.4956,
            -0.2881, -0.1512,  0.0299,  0.1762,  0.2728,  0.2236
            ]
        )
        

        input_speech = self._load_datasample(10)
        feature_extractor = SeamlessM4TFeatureExtractor()
        input_features = feature_extractor(input_speech, return_tensors="pt").input_features

        feature_extractor(input_speech, return_tensors="pt").input_features[0, 5, :30]
        self.assertEqual(input_features.shape, (1, 279, 160))
        self.assertTrue(torch.allclose(input_features[0, 5, :30], EXPECTED_INPUT_FEATURES, atol=1e-4))

    def test_zero_mean_unit_variance_normalization_trunc_np_longest(self):
        feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        audio = self._load_datasample(1)
        audio = ((audio - audio.min()) / (audio.max() - audio.min())) * 65535  
        audio = feat_extract.zero_mean_unit_var_norm([audio], attention_mask=None)[0]

        self.assertTrue((audio.mean() < 1e-3).all())
        self.assertTrue(((audio.var() - 1).abs() < 1e-3).all())