#!/usr/bin/env python3 """Package validated Gemini annotations with exact-audio teacher sidecars. Only individually CC-BY-4.0 S1 audio and user-authorized LAION Talent audio are copied. For third-party mitermix sources without a declared license, this release includes new annotation/vector sidecars plus source references, not audio. """ from __future__ import annotations import hashlib import io import json import os import tarfile from collections import Counter, OrderedDict, defaultdict from pathlib import Path import numpy as np ROOT = Path('/e/scratch/reformo/schuhmann1_moss/whisper_score_regression/' 'gemini_audio_atlas_20261007') TARGETS = Path('/e/scratch/reformo/schuhmann1_moss/whisper_score_regression/' 'gemini_finetune_preparation_20261005/prepared/targets.jsonl') OUT = ROOT / 'dataset' SHARD_SIZE = 128 SOURCE_URLS = { 's1': 'https://huggingface.co/datasets/laion/tts-scaling-ladder-de-en', 'talent': 'https://huggingface.co/datasets/laion/laions_got_talent_raw', 'balanced_40x3k': 'https://huggingface.co/datasets/mitermix/balanced_audio_snippets_40x3k', 'poc': 'https://huggingface.co/datasets/mitermix/voice-annotation-poc', } class TarCache: def __init__(self, max_open=128): self.files = OrderedDict() self.max_open = max_open def read(self, path, name): path = str(path) if path in self.files: tf = self.files.pop(path) else: tf = tarfile.open(path, 'r') self.files[path] = tf while len(self.files) > self.max_open: self.files.popitem(last=False)[1].close() return tf.extractfile(name).read() def close(self): for tf in self.files.values(): tf.close() def add(tf, name, payload): info = tarfile.TarInfo(name) info.size = len(payload) info.mtime = 0 info.mode = 0o644 tf.addfile(info, io.BytesIO(payload)) def source_family(row): sources = {x['source'] for x in row['source_memberships']} for source, family in [('S1_100h', 's1'), ('talent', 'talent'), ('balanced_40x3k', 'balanced_40x3k'), ('poc', 'poc')]: if source in sources: return family raise RuntimeError(f'Unknown memberships {sources}') def audio_policy(row, family): if family == 's1': license_name = str(row['original_annotation'].get('license', '')).lower().replace('_', '-') return license_name in ('cc-by-4.0', 'cc by 4.0'), license_name if family == 'talent': return True, 'CC-BY-4.0 (LAION publisher direction, 2026-10-07)' return False, 'upstream audio license not declared; audio omitted' def public_annotation(row, family, include_audio, audio_license): original = row.get('original_annotation') or {} memberships = [{'source': x['source'], 'bucket': x.get('bucket'), 'uid': x.get('uid')} for x in row['source_memberships']] fields = ['source_dataset', 'hf_source', 'license', 'uid', 'speaker_voice', 'emotion_prompt_slug', 'language', 'source_archive', 'source_member', 'revision', 'selection_reason'] source_detail = {key: original[key] for key in fields if key in original} # This is an annotation release. Do not copy upstream prompt_text, # source transcripts, captions or unlicensed source annotations. return { 'schema_version': 'laion-gemini-voice-annotations-v1', 'sha256_mp3': row['sha256_mp3'], 'duration_s': row['duration_s'], 'split': row['split'], 'source_family': family, 'source_url': SOURCE_URLS[family], 'source_memberships': memberships, 'source_detail': source_detail, 'annotation_license': 'CC-BY-4.0', 'audio_in_shard': include_audio, 'source_audio_license': audio_license, 'gemini_annotation': row['annotation'], 'gemini_provenance': row['annotation_provenance'], 'scalar_targets_raw': row['raw_scores'], 'scalar_target_provenance': row['score_provenance'], 'characters_per_second': row['characters_per_second'], 'cps_source': row['cps_source'], 'vocal_burst_events': row['vocal_bursts'], 'teacher_metadata': row['teacher_metadata'], 'speaker_target_valid': bool((row['teacher_metadata'].get('orange') or {}) .get('valid_single_speaker_target')), 'embedding_file': row['sha256_mp3'] + '.npz', 'notes': 'All non-Gemini scalar/vector targets are predictions by the linked teachers, not human labels. ' 'The entire selected waveform, including any mixture, was passed to the teachers. ' 'Every vocal event has original start and end seconds.' } def vector_payload(row, cache): arrays = {} for kind, dim in [('voiceclap', 768), ('bud_e_pooled', 3072), ('timbre', 128), ('identity', 250)]: spec = (row.get('embeddings') or {}).get(kind) if not spec or spec.get('dim') != dim: raise RuntimeError(f'{row["sha256_mp3"]}: missing {kind} vector metadata') value = np.load(io.BytesIO(cache.read(spec['tar'], spec['member'])), allow_pickle=False) array = np.asarray(value, dtype=np.float16).reshape(-1) if len(array) != dim or not np.isfinite(array).all(): raise RuntimeError(f'{row["sha256_mp3"]}: bad {kind} vector') arrays[kind] = array output = io.BytesIO() np.savez_compressed(output, **arrays) return output.getvalue() class Writer: def __init__(self, folder): self.folder = folder self.folder.mkdir(parents=True, exist_ok=True) self.counter = Counter() self.current = {} def add(self, family, split, sha, audio, annotation, vectors): key = (family, split) n = self.counter[key] shard = n // SHARD_SIZE if key not in self.current or self.current[key][0] != shard: if key in self.current: self.current[key][1].close() self.current[key][2].replace(self.current[key][3]) directory = self.folder / family directory.mkdir(exist_ok=True) final = directory / f'{split}-{shard:04d}.tar' temp = directory / f'{split}-{shard:04d}.tar.incomplete' self.current[key] = (shard, tarfile.open(temp, 'w'), temp, final) tf = self.current[key][1] add(tf, sha + '.json', json.dumps(annotation, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode('utf-8') + b'\n') add(tf, sha + '.npz', vectors) if audio is not None: add(tf, sha + '.mp3', audio) self.counter[key] += 1 return str(self.current[key][3].relative_to(OUT)) def close(self): for _, tf, temp, final in self.current.values(): tf.close() temp.replace(final) def main(): OUT.mkdir(parents=True, exist_ok=True) if (OUT / 'DATASET_READY.json').exists(): raise RuntimeError('Dataset already packaged; refusing to overwrite without review') rows = [] invalid = 0 with TARGETS.open() as source: for line in source: row = json.loads(line) if row.get('gemini_usable') and row.get('ready_for_whisper_training'): rows.append(row) else: invalid += 1 # Group by vector TAR to reuse indexes while resolving 260k vector members. rows.sort(key=lambda row: ((row.get('embeddings') or {}).get('timbre') or {}).get('tar', '')) vectors = TarCache(128) audio_cache = TarCache(128) writer = Writer(OUT / 'data') stats = Counter() seen = set() manifest = OUT / 'manifest.jsonl' example = None with manifest.open('w') as index: for i, row in enumerate(rows, 1): sha = row['sha256_mp3'] if sha in seen: raise RuntimeError(f'Duplicate audio SHA {sha}') seen.add(sha) family = source_family(row) include_audio, license_name = audio_policy(row, family) audio = None if include_audio: audio = audio_cache.read(row['audio_tar'], row['audio_member']) if hashlib.sha256(audio).hexdigest() != sha: raise RuntimeError(f'{sha}: source audio checksum mismatch') annotation = public_annotation(row, family, include_audio, license_name) embedding_bytes = vector_payload(row, vectors) tar = writer.add(family, row['split'], sha, audio, annotation, embedding_bytes) index.write(json.dumps({'sha256_mp3': sha, 'source_family': family, 'split': row['split'], 'tar': tar, 'audio_in_shard': include_audio, 'duration_s': row['duration_s']}) + '\n') stats['valid'] += 1 stats['family_' + family] += 1 stats['split_' + row['split']] += 1 stats['audio_included'] += int(include_audio) stats['annotation_only'] += int(not include_audio) if audio is not None and family == 's1' and len(row['vocal_bursts']) >= 2 and example is None: example = (sha, audio, annotation) if i % 2000 == 0: index.flush(); os.fsync(index.fileno()) print('PACKAGE_PROGRESS', i, '/', len(rows), flush=True) writer.close(); vectors.close(); audio_cache.close() expected = defaultdict(dict) for line in manifest.open(): item = json.loads(line) expected[item['tar']][item['sha256_mp3']] = item verified_audio = 0 for relative, samples in expected.items(): with tarfile.open(OUT / relative, 'r') as tf: names = {member.name for member in tf.getmembers() if member.isfile()} wanted = {sha + suffix for sha, item in samples.items() for suffix in (('.json', '.npz', '.mp3') if item['audio_in_shard'] else ('.json', '.npz'))} if names != wanted: raise RuntimeError(f'{relative}: TAR member set does not match manifest') for sha, item in samples.items(): doc = json.load(tf.extractfile(sha + '.json')) if doc['sha256_mp3'] != sha or doc['audio_in_shard'] != item['audio_in_shard']: raise RuntimeError(f'{relative}/{sha}: JSON sidecar differs') if item['audio_in_shard']: payload = tf.extractfile(sha + '.mp3').read() if hashlib.sha256(payload).hexdigest() != sha: raise RuntimeError(f'{relative}/{sha}: published audio SHA mismatch') verified_audio += 1 if verified_audio != stats['audio_included']: raise RuntimeError('Verified audio count differs from packaged count') if example is None: raise RuntimeError('No licensed multi-event example found') (OUT / 'example.mp3').write_bytes(example[1]) (OUT / 'example.json').write_text(json.dumps(example[2], ensure_ascii=False, indent=2) + '\n') result = {'schema_version': 'laion-gemini-voice-annotations-package-v1', 'valid_annotated': len(rows), 'invalid_or_blocked_excluded': invalid, 'audio_included': stats['audio_included'], 'annotation_only': stats['annotation_only'], 'by_family': {family: stats['family_' + family] for family in SOURCE_URLS}, 'by_split': {split: stats['split_' + split] for split in ('train', 'validation', 'test')}, 'webdataset_shards': sum(len(list((OUT / 'data' / family).glob('*.tar'))) for family in SOURCE_URLS), 'shards_member_sets_verified': len(expected), 'audio_sha256_verified': verified_audio, 'example_sha256': example[0], 'manifest': str(manifest), 'license': 'CC-BY-4.0 for new annotations and included source audio only', 'mitermix_audio': 'omitted: no source license declaration'} (OUT / 'DATASET_READY.json').write_text(json.dumps(result, indent=2) + '\n') print('DATASET_READY', json.dumps(result), flush=True) if __name__ == '__main__': main()