File size: 6,323 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 | #!/usr/bin/env python3
"""Freeze a bounded head-training set before scores, using train phone coverage.
Start from the duration/text-length skeleton. Guarantee up to a fixed number of
distinct train clips for every observed train phone, then fill the fixed budget
from the skeleton and finally the remaining train population. Validation is
copied in full. Test is neither opened nor phonemized.
"""
import argparse
from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path
from adapt_head import dump, load_config, rows, sha, text_key
from tiny_voca.text import frontend_fingerprint, phonemize
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--corpus', type=Path, required=True)
parser.add_argument('--skeleton', type=Path, required=True)
parser.add_argument('--config', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--train-size', type=int, default=2000)
parser.add_argument('--minimum-clips-per-phone', type=int, default=10)
args = parser.parse_args()
if args.output.exists() and any(args.output.iterdir()):
raise FileExistsError('selection output must be new')
config = load_config(args.config)
profile = config.profile
train = rows(args.corpus / 'train.jsonl')
validation = rows(args.corpus / 'validation.jsonl')
skeleton = rows(args.skeleton / 'train.jsonl')
assert all(row['split'] == 'train' for row in train + skeleton)
assert all(row['split'] == 'validation' for row in validation)
rejected, candidates, phone_rows, clip_phones = [], {}, defaultdict(list), {}
for row in train:
ph = phonemize(row['text'], profile)
phones = set(ph.symbols) & profile.phone_set
if ph.unknown or not phones or len(ph.ids) > config.max_tokens:
rejected.append({'id': row['id'], 'reason': 'frontend-structural', 'unknown': list(ph.unknown),
'tokens': len(ph.ids)})
continue
candidates[row['id']] = row
clip_phones[row['id']] = phones
for phone in phones:
phone_rows[phone].append(row['id'])
rank = lambda identifier: hashlib.sha256(('da-v3-head-coverage-v1:' + identifier).encode()).hexdigest()
selected, support = set(), Counter()
for phone in sorted(phone_rows, key=lambda p: (len(phone_rows[p]), p)):
required = min(args.minimum_clips_per_phone, len(phone_rows[phone]))
for identifier in sorted(phone_rows[phone], key=rank):
if support[phone] >= required:
break
if identifier not in selected:
selected.add(identifier)
support.update(clip_phones[identifier])
mandatory = set(selected)
if len(mandatory) > args.train_size:
raise ValueError('phone coverage exceeds budget; change documented protocol before scoring')
for population in ([row['id'] for row in skeleton], list(candidates)):
for identifier in sorted(population, key=rank):
if len(selected) == args.train_size:
break
if identifier in candidates and identifier not in selected:
selected.add(identifier)
support.update(clip_phones[identifier])
if len(selected) != args.train_size:
raise ValueError('not enough structurally valid train clips')
chosen = [candidates[identifier] for identifier in sorted(selected, key=rank)]
seen = set()
train_texts = {text_key(row['text'], profile) for row in chosen}
train_audio = {row['waveform_sha256'] for row in chosen}
if train_texts & {text_key(row['text'], profile) for row in validation}:
raise ValueError('train/validation normalized-text overlap')
if train_audio & {row['waveform_sha256'] for row in validation}:
raise ValueError('train/validation waveform overlap')
args.output.mkdir(parents=True, exist_ok=True)
for split, records in [('train', chosen), ('validation', validation)]:
with (args.output / f'{split}.jsonl').open('w') as stream:
for row in records:
if row['id'] in seen:
raise ValueError('duplicate selected ID')
seen.add(row['id'])
audio = Path(row['audio'])
if not audio.is_absolute():
audio = (args.corpus / audio).resolve()
stream.write(json.dumps({**row, 'audio': str(audio)}, ensure_ascii=False) + '\n')
receipt = {'version': 'da-v3-head-coverage-v1', 'complete': True,
'frontend': frontend_fingerprint(profile),
'selection_uses_predictions_or_qc': False, 'test_opened': False,
'train_count': len(chosen), 'validation_count': len(validation),
'minimum_clips_per_observed_phone': args.minimum_clips_per_phone,
'coverage_mandatory_count': len(mandatory),
'skeleton_retained': len(selected & {row['id'] for row in skeleton}),
'selection_order': 'rarest-train-phones first; SHA256-ranked clip IDs; skeleton then remainder fills budget',
'train_seconds': sum(row['duration_seconds'] for row in chosen),
'validation_seconds': sum(row['duration_seconds'] for row in validation),
'training_population_phone_clips': dict(sorted((p, len(ids)) for p,ids in phone_rows.items())),
'selected_phone_clips': dict(sorted(support.items())),
'unobserved_inventory_phones': sorted(profile.phone_set - phone_rows.keys()),
'structurally_rejected_candidates': rejected,
'sources': {str(path.resolve()): sha(path) for path in [args.corpus / 'train.jsonl',
args.corpus / 'validation.jsonl', args.skeleton / 'train.jsonl', args.skeleton / 'receipt.json']},
'outputs': {f'{split}.jsonl': sha(args.output / f'{split}.jsonl') for split in ('train','validation')}}
dump(args.output / 'selection.json', receipt)
print(json.dumps({key:receipt[key] for key in ['frontend','train_count','validation_count',
'coverage_mandatory_count','skeleton_retained','train_seconds','validation_seconds']}, indent=2))
if __name__ == '__main__':
main()
|