File size: 7,260 Bytes
42ba33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python3
"""Select a licensed, reproducible listening pool and diverse burst candidates."""
from __future__ import annotations

import hashlib
import json
from collections import Counter, defaultdict
from pathlib import Path

TARGETS = Path('/e/scratch/reformo/schuhmann1_moss/whisper_score_regression/'
               'gemini_finetune_preparation_20261005/prepared/targets.jsonl')
OUT = Path('/e/scratch/reformo/schuhmann1_moss/whisper_score_regression/'
           'gemini_audio_atlas_20261007')
SEED = 'whisper-gemini-atlas-20261007-v1'
POOL_SIZE = 1000
CANDIDATES = 300


def rank(*parts: str) -> str:
    return hashlib.sha256(('|'.join((SEED, *parts))).encode()).hexdigest()


def eligible(row: dict) -> bool:
    original = row.get('original_annotation') or {}
    sources = {m.get('source') for m in row.get('source_memberships', [])}
    license_name = str(original.get('license', '')).strip().lower().replace('_', '-')
    return bool(row.get('gemini_usable') and row.get('ready_for_whisper_training')
                and row.get('split') in ('test', 'validation')
                and 'S1_100h' in sources
                and license_name in ('cc-by-4.0', 'cc by 4.0')
                and row.get('audio_tar') and row.get('audio_member')
                and (row.get('embeddings') or {}).get('timbre', {}).get('dim') == 128
                and (row.get('embeddings') or {}).get('identity', {}).get('dim') == 250)


def compact(row: dict) -> dict:
    original = row['original_annotation']
    events = [{'start_s': float(v['start']), 'end_s': float(v['end']),
               'fine': v.get('fine'), 'group23': v.get('group23')}
              for v in row.get('vocal_bursts', [])
              if v.get('start') is not None and v.get('end') is not None]
    return {
        'sha256_mp3': row['sha256_mp3'], 'duration_s': row['duration_s'],
        'audio_tar': row['audio_tar'], 'audio_member': row['audio_member'],
        'split': row['split'], 'source_dataset': original.get('source_dataset'),
        'source_uid': original.get('uid'), 'source_license': original.get('license'),
        'source_url': original.get('hf_source'),
        'language_source': original.get('language_source'),
        'gemini_language': (row.get('annotation') or {}).get('language'),
        'gemini_burst_events': events,
        'teacher_timbre': row['embeddings']['timbre'],
        'teacher_identity': row['embeddings']['identity'],
        'speaker_target_valid': bool((row.get('teacher_metadata') or {}).get('orange', {})
                                     .get('valid_single_speaker_target')),
    }


def diverse_pool(rows: list[dict]) -> list[dict]:
    # Prefer the Gemini fine-tune test split, then its validation split if the
    # Emolia source alone has fewer than 1,000 licensed examples.
    choices = sorted(rows, key=lambda r: (0 if r['split'] == 'test' else 1,
                                          rank('pool', r['sha256_mp3'])))
    by_language = defaultdict(list)
    for r in choices:
        by_language[str(r['language_source']).split('/')[0]].append(r)
    chosen, used = [], set()
    langs = sorted(by_language)
    if len(langs) >= 2:
        for lang in langs:
            for row in by_language[lang][:POOL_SIZE // len(langs)]:
                chosen.append(row); used.add(row['sha256_mp3'])
    for row in choices:
        if len(chosen) >= POOL_SIZE:
            break
        if row['sha256_mp3'] not in used:
            chosen.append(row); used.add(row['sha256_mp3'])
    return chosen


def burst_candidates(rows: list[dict], exclude: set[str]) -> list[dict]:
    groups = Counter(event['group23'] for row in rows
                     for event in row['gemini_burst_events'] if event.get('group23'))
    by_primary = defaultdict(list)
    for row in rows:
        if row['sha256_mp3'] in exclude or not row['gemini_burst_events']:
            continue
        group_names = {e['group23'] for e in row['gemini_burst_events'] if e.get('group23')}
        if not group_names:
            continue
        primary = min(group_names, key=lambda name: (groups[name], name))
        by_primary[primary].append(row)
    for group in by_primary:
        by_primary[group].sort(key=lambda row: (
            0 if row['split'] == 'test' else 1,
            -len(row['gemini_burst_events']), rank('burst', row['sha256_mp3'])))
    chosen, used = [], set()
    for position in range(12):
        for group in sorted(by_primary, key=lambda name: (groups[name], name)):
            candidates = by_primary[group]
            if position >= len(candidates):
                continue
            row = candidates[position]
            if row['sha256_mp3'] not in used:
                chosen.append(row); used.add(row['sha256_mp3'])
            if len(chosen) >= CANDIDATES:
                return chosen
    for row in sorted(rows, key=lambda r: rank('burst-fill', r['sha256_mp3'])):
        if len(chosen) >= CANDIDATES:
            break
        if row['gemini_burst_events'] and row['sha256_mp3'] not in used and row['sha256_mp3'] not in exclude:
            chosen.append(row); used.add(row['sha256_mp3'])
    return chosen


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    emolia, burst_rows = [], []
    stats = Counter()
    with TARGETS.open() as source:
        for line in source:
            row = json.loads(line)
            if not eligible(row):
                continue
            item = compact(row)
            stats['eligible_s1_cc_by'] += 1
            stats['split_' + item['split']] += 1
            if item['source_dataset'] == 'emolia':
                emolia.append(item)
                stats['emolia_eligible'] += 1
                stats['emolia_' + item['split']] += 1
            if item['gemini_burst_events']:
                burst_rows.append(item)
    if len(emolia) < POOL_SIZE:
        raise RuntimeError(f'Only {len(emolia)} eligible Emolia examples; need {POOL_SIZE}')
    pool = diverse_pool(emolia)
    if len(pool) != POOL_SIZE:
        raise RuntimeError(f'Pool has {len(pool)}, expected {POOL_SIZE}')
    candidates = burst_candidates(burst_rows, {r['sha256_mp3'] for r in pool})
    if len(candidates) < 50:
        raise RuntimeError(f'Only {len(candidates)} burst candidates; need at least 50')
    all_rows = {r['sha256_mp3']: r for r in pool + candidates}
    for filename, rows in [('pool.jsonl', pool), ('burst_candidates.jsonl', candidates),
                           ('inference_manifest.jsonl', list(all_rows.values()))]:
        with (OUT / filename).open('w') as target:
            for row in rows:
                target.write(json.dumps(row, ensure_ascii=False) + '\n')
    stats.update(pool=len(pool), burst_candidates=len(candidates),
                 inference_unique=len(all_rows))
    stats['pool_by_split'] = dict(Counter(r['split'] for r in pool))
    stats['pool_by_language'] = dict(Counter(r['language_source'] for r in pool))
    stats['burst_candidate_group_events'] = dict(Counter(
        e['group23'] for row in candidates for e in row['gemini_burst_events']))
    (OUT / 'selection_summary.json').write_text(json.dumps(stats, indent=2) + '\n')
    print(json.dumps(stats, indent=2), flush=True)


if __name__ == '__main__':
    main()