File size: 7,767 Bytes
4689281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""Offline coverage of the collector, Hub commit boundary, and training reader."""
import io
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch

import numpy as np
import pyarrow.parquet as pq
import torch
from datasets import Audio, ClassLabel, Dataset
from scipy.io import wavfile

import kaggle_data_collector as c
from data.dataset import MurliV2Dataset, v2_collate_fn


def audio(freq, sr=24000, seconds=2):
    samples = np.arange(round(sr * seconds)) / sr
    buf = io.BytesIO()
    wavfile.write(buf, sr, (5000 * np.sin(2 * np.pi * freq * samples)).astype("int16"))
    return {"bytes": buf.getvalue(), "path": "test.wav"}


class Hub:
    def __init__(self, directory):
        self.directory = Path(directory)
        self.rev = 1
        self.commits = []
        self.disconnect = False

    def create_repo(self, *args, **kwargs):
        pass

    def dataset_info(self, *args, **kwargs):
        return SimpleNamespace(sha=str(self.rev))

    def list_repo_files(self, *args, **kwargs):
        return [p.relative_to(self.directory).as_posix() for p in self.directory.rglob("*") if p.is_file()]

    def create_commit(self, *, operations, parent_commit, **kwargs):
        if str(self.rev) != parent_commit:
            raise ValueError("conflicting writer")
        paths = []
        for op in operations:
            dest = self.directory / op.path_in_repo
            dest.parent.mkdir(parents=True, exist_ok=True)
            with op.as_file() as file:
                dest.write_bytes(file.read())
            paths.append(op.path_in_repo)
        self.commits.append(paths)
        self.rev += 1
        if self.disconnect:
            self.disconnect = False
            raise OSError("Lost response after successful commit")
        return SimpleNamespace(oid=str(self.rev))

    def download(self, repo, path, **kwargs):
        return str(self.directory / path)


class CollectorTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.threads = torch.get_num_threads()
        torch.set_num_threads(1)

    @classmethod
    def tearDownClass(cls):
        torch.set_num_threads(cls.threads)

    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.addCleanup(self.tmp.cleanup)
        self.hub = Hub(self.tmp.name)
        self.enterContext(patch.object(c, "HfApi", return_value=self.hub))
        self.enterContext(patch.object(c, "hf_hub_download", side_effect=self.hub.download))
        self.src = next(s for s in c.SOURCES if s.name == "english_mls")
        rows = [{"audio": audio(f), "transcript": "Hello from the speech dataset", "speaker_id": "s"}
                for f in [220, 220, 330]]
        self.ds = Dataset.from_list(rows).cast_column("audio", Audio(decode=False)).to_iterable_dataset()
        self.loader = self.enterContext(patch.object(c, "load_dataset", return_value=self.ds))

    def curator(self, mb=1):
        curator = c.StreamingBilingualCurator("test/repo", mb, None)
        curator.initialize()
        return curator

    def test_commit_resume_dedup_and_training_batch(self):
        curator = self.curator(0.02)
        self.hub.disconnect = True
        with self.assertRaises(c.CommitFailure):
            curator.collect(self.src, 1)
        self.assertEqual(len(self.hub.commits[-1]), 3)
        revision = self.loader.call_args.kwargs["revision"]
        curator = self.curator(0.02)
        curator.collect(self.src, 1)
        self.assertEqual(self.loader.call_args.kwargs["revision"], revision)
        st = curator.states[self.src.name]
        self.assertEqual((st["curated_clips"], st["rows_seen"], st["rejected"]), (2, 3, {"duplicate_audio": 1}))
        self.assertTrue(st["exhausted"])
        self.assertAlmostEqual(st["curated_hours"], 4 / 3600)
        self.assertEqual(c.run(curator, {"hi": 0, "en": 1}, self.src.name), 1)
        train = MurliV2Dataset(parquet_dir=self.tmp.name)
        self.assertEqual(len(train), 2)
        batch = v2_collate_fn([train[1], train[0]])
        self.assertEqual(batch["mel_target"].shape[:2], (2, 100))
        self.assertTrue(torch.isfinite(batch["mel_target"]).all())

    def test_language_budget_uses_previously_saved_sources(self):
        curator = self.curator()
        curator.states["english_libritts_r_100"]["curated_hours"] = 9.5
        with patch.object(curator, "collect") as collect:
            c.run(curator, {"hi": 0, "en": 10}, self.src.name)
        collect.assert_called_once_with(self.src, 0.5)

    def test_preexisting_shard_without_checkpoint(self):
        curator = self.curator()
        curator.collect(self.src, 1 / 3600)
        folder = self.hub.directory / c.ROOT / self.src.name
        shard = next(folder.glob("*.parquet"))
        (folder / "_state.json").unlink()
        (folder / (shard.name + ".idx.gz")).unlink()
        curator = self.curator()
        self.assertEqual(curator.states[self.src.name]["curated_clips"], 1)
        curator.collect(self.src, 1)
        self.assertEqual(curator.states[self.src.name]["curated_clips"], 2)
        self.assertEqual(sum(pq.read_metadata(p).num_rows for p in folder.glob("*.parquet")), 2)

    def test_legacy_untouched_card_and_conflict(self):
        readme = self.hub.directory / "README.md"
        readme.write_text("My dataset card")
        first, second = self.curator(), self.curator()
        first.collect(self.src, 1 / 3600)
        with self.assertRaises(c.CommitFailure):
            second.collect(self.src, 1 / 3600)
        self.assertEqual(readme.read_text(), "My dataset card")

    def test_quality_labels_and_overlapping_source(self):
        src = next(s for s in c.SOURCES if s.name == "hindi_indictts")
        text = "यह एक वाक्य है"
        mapped = c.metadata({"text":text, "gender":0}, src, {"gender": ClassLabel(names=["female","male"])})
        self.assertEqual(mapped, (text, "indictts_hi_female", "female"))
        one = c.fingerprint_keys(b"a", text, src.name, mapped[1])
        two = c.fingerprint_keys(b"b", text, "hindi_kalita", "kalita_indictts_female_01")
        self.assertEqual(one[1], two[1])
        wav, seconds, previous = c.prepare_audio(audio(440, sr=48000), "this is a sample", True)
        self.assertIsNotNone(previous)
        self.assertEqual(wavfile.read(io.BytesIO(wav))[0], 24000)
        self.assertAlmostEqual(seconds, 2)
        with self.assertRaises(c.Reject):
            c.prepare_audio(audio(0), "silence")
        with self.assertRaises(c.Reject):
            c.prepare_audio(audio(220, seconds=0.5), "too short")

    def test_hindi_source_filters_and_training_holdout(self):
        hindi = next(s for s in c.SOURCES if s.name == "hindi_indicvoices_r")
        with self.assertRaisesRegex(c.Reject, "transcript_cer"):
            c.metadata({"text": "एक वाक्य", "snr": 35, "cer": "tensor(0.4)"}, hindi, {})
        hindi_row = c.metadata({"text": "एक वाक्य", "snr": 35, "cer": "tensor(0.04)"}, hindi, {})
        self.assertEqual(hindi_row[0], "एक वाक्य")
        train = MurliV2Dataset(partition="train")
        val = MurliV2Dataset(partition="validation")
        rows = [{"text": "example", "speaker_id": f"s{i}"} for i in range(500)]
        training = {r["speaker_id"] for r in rows if train._accept_row(r, None, None)}
        held_out = {r["speaker_id"] for r in rows if val._accept_row(r, None, None)}
        self.assertTrue(held_out)
        self.assertFalse(training & held_out)
        self.assertEqual(len(training | held_out), len(rows))
        self.assertFalse(val._accept_row({"text": "example", "speaker_id": "ivr_unknown"}, None, None))


if __name__ == "__main__":
    unittest.main()