#!/usr/bin/env python3 """Check every prepared acoustic row, compact waveform and source split identity.""" import argparse import collections import hashlib import json from pathlib import Path import torch from tiny_voca.config import Config from tiny_voca.feature_io import load_feature, wave_path, waveform_hash def rows(path): return [json.loads(line) for line in path.read_text().split('\n') if line.strip()] def sha(path): h = hashlib.sha256() with path.open('rb') as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b''): h.update(chunk) return h.hexdigest() def check(features, source, config): features, source = features.resolve(), source.resolve() schema = json.loads((features / 'features.json').read_text()) if schema['fingerprint'] != config.acoustic_fingerprint: raise ValueError('Acoustic fingerprint differs') report = {'status': 'RUNNING', 'acoustic_fingerprint': config.acoustic_fingerprint, 'storage': schema.get('storage', 'inline-float32-v1'), 'splits': {}, 'errors': [], 'waveform_identity': 'sample-rate-channels-frames-float32le-v1', 'container_hash_role': 'provenance'} inventory = [] seen = {key: {} for key in ('id', 'text_id', 'waveform_sha256')} for split in ('train', 'validation', 'test'): receipt = json.loads((features / (split + '.preparation.json')).read_text()) if not receipt.get('complete'): raise ValueError(f'Incomplete preparation: {split}') expected = {row['id']: row for row in rows(source / (split + '.jsonl'))} accepted = rows(features / (split + '.jsonl')) rejected = rows(features / (split + '.rejected.jsonl')) accepted_ids = {row['id'] for row in accepted} rejected_ids = {row['id'] for row in rejected} if len(accepted_ids) != len(accepted) or len(rejected_ids) != len(rejected) or accepted_ids & rejected_ids: raise ValueError(f'Duplicate/overlapping accepted/rejected IDs: {split}') if accepted_ids | rejected_ids != expected.keys(): raise ValueError(f'Source rows were dropped or invented: {split}') if receipt['accepted'] != len(accepted) or receipt['rejected'] != len(rejected): raise ValueError(f'Counts differ from preparation receipt: {split}') frames = feature_bytes = original_containers = changed_headers = 0 for row in accepted: original = expected[row['id']] path = (features / row['path']).resolve() if not path.is_relative_to(features): raise ValueError('Feature escapes acoustic root') item = load_feature(path, root=features) t = row['frames'] if item['wave'].shape != (t * config.hop,) or item['mel'].shape != (t, config.n_mels) or item['prosody'].shape != (t, 3): raise ValueError(f'Feature shape mismatch: {row["id"]}') if any(item[key].dtype != torch.float32 or not torch.isfinite(item[key]).all() for key in ('wave', 'mel', 'prosody')): raise ValueError(f'Invalid float32 values: {row["id"]}') if row['text'] != original['text'] or row['speaker'] != original['voice_id']: raise ValueError(f'Text/speaker changed: {row["id"]}') ref = item.get('wave_ref') if ref: sample_hash = ref['waveform_sha256'] if sample_hash != original['waveform_sha256']: raise ValueError(f'Waveform differs from original source: {row["id"]}') samples = ref['samples'] if bool(torch.count_nonzero(item['wave'][samples:])): raise ValueError('Non-zero padding') audio = wave_path(ref, features) audio_bytes = audio.stat().st_size actual_container_sha = sha(audio) if actual_container_sha == original['audio_sha256']: original_containers += 1 else: changed_headers += 1 # Exact decoded samples were already verified. else: samples = round(original['duration_seconds'] * config.sample_rate) sample_hash = waveform_hash(item['wave'][:samples].numpy(), config.sample_rate) if sample_hash != original['waveform_sha256']: raise ValueError('Legacy feature waveform differs from source') audio_bytes = 0 actual_container_sha = None identities = {'id': row['id'], 'text_id': original['text_id'], 'waveform_sha256': sample_hash} for key, value in identities.items(): if value in seen[key] and (key != 'text_id' or seen[key][value] != split): raise ValueError(f'Duplicate/cross-split {key}: {row["id"]}') seen[key][value] = split size = path.stat().st_size frames += t feature_bytes += size inventory.append({'id': row['id'], 'split': split, 'path': row['path'], 'feature_sha256': sha(path), 'feature_bytes': size, 'waveform_sha256': sample_hash, 'samples': samples, 'recording_bytes': audio_bytes, 'recording_container_sha256': actual_container_sha, 'frames': t}) report['splits'][split] = {'source': len(expected), 'accepted': len(accepted), 'rejected': len(rejected), 'rejection_reasons': dict(collections.Counter(row['reason'] for row in rejected)), 'frames': frames, 'padded_seconds': frames * config.hop / config.sample_rate, 'original_container_sha_matches': original_containers, 'different_container_same_waveform': changed_headers, 'feature_bytes': feature_bytes, 'manifest_sha256': sha(features / (split + '.jsonl'))} report.update(status='PASS', checked=sum(x['accepted'] for x in report['splits'].values()), unique_ids=len(seen['id']), unique_waveforms=len(seen['waveform_sha256']), unique_texts=len(seen['text_id']), cross_split_id_text_wave_leakage=0) return report, inventory def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--features', type=Path, required=True) parser.add_argument('--source', type=Path, required=True) parser.add_argument('--config', type=Path, required=True) parser.add_argument('--report', type=Path, required=True) args = parser.parse_args() config = Config.from_dict(json.loads(args.config.read_text())) report, inventory = check(args.features, args.source, config) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') args.report.with_suffix('.inventory.jsonl').write_text(''.join(json.dumps(row) + '\n' for row in inventory)) print(json.dumps(report, ensure_ascii=False, indent=2)) if __name__ == '__main__': main()