File size: 6,401 Bytes
adabee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import hashlib
import json
from pathlib import Path
import shutil
import sys
import tempfile
import unittest
from unittest.mock import patch

import numpy as np
import soundfile as sf
import torch

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pack_prepared
from prepare_coral import record_id
from restore_feature_audio import restore_hub, restore_local
from tiny_voca.config import Config
from tiny_voca.data import AnnotatedDataset
from tiny_voca.feature_io import load_feature, store_wave_reference
from tiny_voca.text import frontend_fingerprint


class CompactBundleTests(unittest.TestCase):
    def test_pack_relocate_remove_source_restore_and_load_exact_wave(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            source = root / 'source'
            corpus = root / 'corpus'
            corpus.mkdir()
            features = source / 'features'
            annotations = source / 'annotations'
            annotations.mkdir(parents=True)
            config = Config()
            config_path = root / 'config.json'
            config_path.write_text(json.dumps(config.to_dict()))
            originals = {}
            for index, split in enumerate(('train', 'validation', 'test')):
                identifier = split + '-fixture'
                wave = (0.1 * np.sin(np.arange(2560) * (0.03 + index * 0.01))).astype('float32')
                recording = corpus / (identifier + '.wav')
                sf.write(recording, wave, 24000, subtype='FLOAT')
                ref = store_wave_reference(str(recording), wave, 24000, 256, features, identifier)
                path = f'{split}/clip.pt'
                (features / split).mkdir()
                torch.save({'mel': torch.randn(10, 80), 'prosody': torch.zeros(10, 3), 'speaker': 0, 'wave_ref': ref}, features / path)
                row = {'id': identifier, 'text': split + ' fixture.', 'speaker': 'F2', 'path': path,
                       'tokens': [1, config.profile.symbols.index('h'), config.profile.symbols.index('ə'), 2],
                       'stress': [0, 0, 0, 0], 'durations': [1, 2, 3, 4], 'frames': 10,
                       'frontend': frontend_fingerprint(config.profile), 'acoustic': config.acoustic_fingerprint,
                       'annotation': 'synthetic-test-only', 'provenance': {'source_license': 'test-synthetic'}}
                (annotations / (split + '.jsonl')).write_text(json.dumps(row) + '\n')
                (corpus / (split + '.jsonl')).write_text(json.dumps({'id': identifier, 'audio': recording.name}) + '\n')
                originals[split] = wave
            (annotations / 'annotations.json').write_text(json.dumps({'complete': True, 'fingerprint': 'synthetic-test-only',
                                                                      'synthetic_test_only': True, 'acoustic_root': str(features)}))
            bundle = root / 'bundle'
            argv = ['pack_prepared.py', '--annotations', str(annotations), '--config', str(config_path),
                    '--output', str(bundle), '--audio-mode', 'hardlink', '--feature-mode', 'hardlink', '--archive-without-audio']
            with patch.object(sys, 'argv', argv):
                pack_prepared.main()
            for split in originals:
                self.assertEqual((annotations / (split + '.jsonl')).read_bytes(),
                                 (bundle / 'annotations' / (split + '.jsonl')).read_bytes())
                self.assertEqual((features / split / 'clip.pt').stat().st_ino,
                                 (bundle / 'features' / split / 'clip.pt').stat().st_ino)
            report = json.loads((bundle / 'receipt.json').read_text())
            self.assertFalse(report['archive_audio_included'])
            self.assertEqual(report['actual_staging_modes']['features'], {'hardlink': 3})
            self.assertFalse(any(path.startswith('features/audio/') for path in report['files']))
            self.assertEqual(len(report['audio_container_sha256_provenance']), 3)
            shutil.rmtree(source)
            relocated = root / 'relocated'
            bundle.rename(relocated)
            sources = [json.loads(x) for x in (relocated / 'audio_sources.jsonl').read_text().split('\n') if x.strip()]
            for row in sources:
                (relocated / row['path']).unlink()
            counts = restore_local(sources, corpus, relocated)
            self.assertEqual(counts['hardlinked'], 3)
            for split, wave in originals.items():
                ds = AnnotatedDataset(relocated / 'annotations' / (split + '.jsonl'), config, cache=False)
                self.assertTrue(torch.equal(ds[0]['wave'], torch.from_numpy(wave)))

    def test_hub_restoration_checks_source_and_exact_samples_without_frontend(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            wave = (0.1 * np.sin(np.arange(12003) * 0.03)).astype('float32')
            original = root / 'original.wav'
            sf.write(original, wave, 24000, subtype='FLOAT')
            payload = original.read_bytes()
            encoded_sha = hashlib.sha256(payload).hexdigest()
            identifier = record_id('mic', 123, encoded_sha)
            ref = store_wave_reference(str(original), wave, 24000, 256, root / 'old', identifier)
            row = {'id': identifier, 'path': 'features/' + ref['path'], 'wave_ref': ref,
                   'provenance': {'origin': 'CoRal-project/coral-tts', 'source_id': 'mic:123',
                                  'source_revision': '1' * 40, 'source_audio_sha256': encoded_sha}}
            raw = {'speaker_id': 'mic', 'transcription_id': 123, 'audio': {'bytes': payload}}
            with patch('prepare_coral.load_rows', return_value=iter([raw])):
                counts = restore_hub([row], root / 'new')
            self.assertEqual(counts['downloaded_and_verified'], 1)
            restored, rate = sf.read(root / 'new' / row['path'], dtype='float32')
            self.assertEqual(rate, 24000)
            self.assertTrue(np.array_equal(wave, restored))
            row['provenance']['source_audio_sha256'] = '0' * 64
            with patch('prepare_coral.load_rows', return_value=iter([raw])):
                with self.assertRaisesRegex(ValueError, 'source audio checksum'):
                    restore_hub([row], root / 'bad')


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