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