File size: 6,525 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
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python3
"""Check all three annotation manifests using the trainer's own dataset reader."""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
from tiny_voca.config import Config
from tiny_voca.data import AnnotatedDataset
from tiny_voca.feature_io import load_feature
from tiny_voca.text import normalize_text


def file_sha256(path):
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()


def bound_waveform_identity(stored, row):
    """Bind a verified compact recording to the annotation's source waveform."""
    expected = row.get('provenance', {}).get('waveform_sha256')
    if 'wave_ref' in stored:
        actual = stored['wave_ref'].get('waveform_sha256')
        if not expected or actual != expected:
            raise ValueError(f'Loaded feature waveform differs from annotation: {row["id"]}')
        return actual
    # Legacy inline tensors lack their unpadded sample count. Their provenance
    # can support the old leakage check, but is not counted as a compact binding.
    return expected


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--annotations', type=Path, required=True)
    p.add_argument('--config', type=Path, required=True)
    p.add_argument('--output', type=Path, required=True)
    p.add_argument('--load-features', action='store_true')
    args = p.parse_args()
    c = Config.from_dict(json.loads(args.config.read_text()))
    meta = json.loads((args.annotations / 'annotations.json').read_text())
    if meta.get('synthetic_test_only'):
        raise SystemExit('Synthetic fixtures are not accepted as real training data.')
    if not meta.get('complete'):
        raise SystemExit('Incomplete annotations: finish the run with --resume; do not change complete manually.')
    seen_ids, seen_texts, seen_waves = {}, {}, {}
    report = {'language': c.language, 'profile_digest': c.profile.digest,
              'annotation_fingerprint': meta['fingerprint'], 'complete': False,
              'annotation_metadata_sha256': file_sha256(args.annotations / 'annotations.json'),
              'manifest_sha256': {}, 'load_features': args.load_features,
              'compact_waveform_identities_bound': 0, 'splits': {}, 'errors': []}
    all_source_ids = set()
    for split in ('train', 'validation', 'test'):
        required = [args.annotations / f'{split}.jsonl', args.annotations / f'{split}.rejected.jsonl']
        missing = [path.name for path in required if not path.is_file()]
        if missing:
            report['errors'].append(f'{split}: missing required manifests: {missing}')
            report['splits'][split] = {'error': 'missing required accepted/rejected manifests'}
            continue
        for path in required:
            report['manifest_sha256'][path.name] = file_sha256(path)
        with required[1].open(encoding='utf-8') as stream:
            rejected = [json.loads(line) for line in stream if line.strip()]
        try:
            ds = AnnotatedDataset(args.annotations / f'{split}.jsonl', c, cache=False)
        except (ValueError, OSError) as error:
            report['errors'].append(f'{split}: {error}')
            report['splits'][split] = {'error': str(error)}
            continue
        accepted_ids = [row['id'] for row in ds.rows]
        rejected_ids = [row['id'] for row in rejected]
        combined = accepted_ids + rejected_ids
        if len(combined) != len(set(combined)) or set(combined) & all_source_ids:
            report['errors'].append(f'{split}: duplicate or overlapping accepted/rejected source IDs')
        all_source_ids.update(combined)
        if len(ds) != meta.get('counts', {}).get(split):
            report['errors'].append(f'{split}: accepted manifest count differs from metadata')
        if len(rejected) != meta.get('rejected_counts', {}).get(split):
            report['errors'].append(f'{split}: rejected manifest count differs from metadata')
        if any(not row.get('reasons') for row in rejected):
            report['errors'].append(f'{split}: rejected row has no rejection reason')
        for index, row in enumerate(ds.rows):
            text_key = normalize_text(row['text'], c.profile).casefold()
            for key, seen, kind in ((row['id'], seen_ids, 'id'), (text_key, seen_texts, 'normalized text')):
                if key in seen and seen[key] != split:
                    raise ValueError(f'{kind} leaks between {seen[key]} and {split}: {row["id"]}')
                seen[key] = split
            if row.get('unknown'):
                raise ValueError(f'Unknown phonemes: {row["id"]}')
            if args.load_features:
                ds[index]
                stored = load_feature(ds.row_roots[index] / row['path'], root=ds.row_roots[index])
                wave_hash = bound_waveform_identity(stored, row)
                if 'wave_ref' in stored:
                    report['compact_waveform_identities_bound'] += 1
                if wave_hash:
                    if wave_hash in seen_waves and seen_waves[wave_hash] != split:
                        raise ValueError(f'decoded waveform leaks between {seen_waves[wave_hash]} and {split}: {row["id"]}')
                    seen_waves[wave_hash] = split
        reasons = Counter(reason for row in rejected for reason in row.get('reasons', []))
        report['splits'][split] = {'accepted': len(ds), 'rejected': len(rejected),
                                  'audio_seconds': sum(ds.lengths) * c.hop / c.sample_rate,
                                  'rejection_reasons': dict(reasons)}
    for name, digest in report['manifest_sha256'].items():
        if file_sha256(args.annotations / name) != digest:
            report['errors'].append(f'manifest changed during validation: {name}')
    if file_sha256(args.annotations / 'annotations.json') != report['annotation_metadata_sha256']:
        report['errors'].append('annotation metadata changed during validation')
    report['complete'] = not report['errors']
    report['unique_waveforms_checked'] = len(seen_waves)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + '\n')
    print(json.dumps(report, ensure_ascii=False, indent=2))
    raise SystemExit(1 if report['errors'] else 0)


if __name__ == '__main__':
    main()