Download recipe/kit-v3/tests/test_compact_bundle.py from gowombat/tiny-voca-da: direct link, hf CLI and curl.
- Browser
- Download file 6.4 kB
-
https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/kit-v3/tests/test_compact_bundle.py
- Command line
-
hf download hf://gowombat/tiny-voca-da/recipe/kit-v3/tests/test_compact_bundle.py
-
curl -L -o test_compact_bundle.py https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/kit-v3/tests/test_compact_bundle.py
6.4 kB
| 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() | |