|
| 1 | +import unittest |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +from transformers import pipeline |
| 6 | +from transformers.testing_utils import require_torch |
| 7 | + |
| 8 | + |
| 9 | +@require_torch |
| 10 | +class AudioClassificationTopKTest(unittest.TestCase): |
| 11 | + def test_top_k_none_returns_all_labels(self): |
| 12 | + model_name = "superb/wav2vec2-base-superb-ks" # model with more than 5 labels |
| 13 | + classification_pipeline = pipeline( |
| 14 | + "audio-classification", |
| 15 | + model=model_name, |
| 16 | + top_k=None, |
| 17 | + ) |
| 18 | + |
| 19 | + # Create dummy input |
| 20 | + sampling_rate = 16000 |
| 21 | + signal = np.zeros((sampling_rate,), dtype=np.float32) |
| 22 | + |
| 23 | + result = classification_pipeline(signal) |
| 24 | + num_labels = classification_pipeline.model.config.num_labels |
| 25 | + |
| 26 | + self.assertEqual(len(result), num_labels, "Should return all labels when top_k is None") |
| 27 | + |
| 28 | + def test_top_k_none_with_few_labels(self): |
| 29 | + model_name = "superb/hubert-base-superb-er" # model with fewer labels |
| 30 | + classification_pipeline = pipeline( |
| 31 | + "audio-classification", |
| 32 | + model=model_name, |
| 33 | + top_k=None, |
| 34 | + ) |
| 35 | + |
| 36 | + # Create dummy input |
| 37 | + sampling_rate = 16000 |
| 38 | + signal = np.zeros((sampling_rate,), dtype=np.float32) |
| 39 | + |
| 40 | + result = classification_pipeline(signal) |
| 41 | + num_labels = classification_pipeline.model.config.num_labels |
| 42 | + |
| 43 | + self.assertEqual(len(result), num_labels, "Should handle models with fewer labels correctly") |
| 44 | + |
| 45 | + def test_top_k_greater_than_labels(self): |
| 46 | + model_name = "superb/hubert-base-superb-er" |
| 47 | + classification_pipeline = pipeline( |
| 48 | + "audio-classification", |
| 49 | + model=model_name, |
| 50 | + top_k=100, # intentionally large number |
| 51 | + ) |
| 52 | + |
| 53 | + # Create dummy input |
| 54 | + sampling_rate = 16000 |
| 55 | + signal = np.zeros((sampling_rate,), dtype=np.float32) |
| 56 | + |
| 57 | + result = classification_pipeline(signal) |
| 58 | + num_labels = classification_pipeline.model.config.num_labels |
| 59 | + |
| 60 | + self.assertEqual(len(result), num_labels, "Should cap top_k to number of labels") |
0 commit comments