humaneness-ears-atlas / code /select_pool.py
ChristophSchuhmann's picture
Add files using upload-large-folder tool
42ba33d verified
Raw History Blame Contribute Delete
7.26 kB
#!/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()