Datasets:
File size: 4,376 Bytes
f570fd9 | 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 | """Export this release's alignment Parquet files to nano-duplex raw WAV/JSONL.
Example: python materialize_alignment.py --snapshot ./nano-duplex-data-v1 --output ./raw --split train
Dependencies: numpy, pyarrow, soundfile. No torchcodec or remote dataset code is required.
"""
from __future__ import annotations
import argparse
import hashlib
from io import BytesIO
import json
from pathlib import Path
import re
import numpy as np
import pyarrow.parquet as pq
import soundfile as sf
def materialize(snapshot, output, split, limit=None):
snapshot, output = Path(snapshot), Path(output)
files = sorted((snapshot / 'alignment').glob(f'{split}-*.parquet'))
if not files:
raise ValueError('No alignment shards for the requested split')
if limit is not None and limit <= 0:
raise ValueError('Limit must be positive')
output.mkdir(parents=True, exist_ok=True)
audio_directory = output / 'audio' / split
audio_directory.mkdir(parents=True, exist_ok=True)
manifest = output / f'{split}.jsonl'
if manifest.exists():
raise FileExistsError('Use a fresh output directory to preserve existing training manifests')
temporary = manifest.with_suffix('.jsonl.tmp')
count = 0
with temporary.open('w', encoding='utf-8', newline='\n') as target:
for file in files:
for batch in pq.ParquetFile(file).iter_batches(batch_size=16):
for row in batch.to_pylist():
if not re.fullmatch(r'\d+_\d+_\d+_\d+', row['original_id']):
raise ValueError('Unexpected original utterance identifier')
pcm, rate = sf.read(BytesIO(row['audio']['bytes']), dtype='int16')
digest = hashlib.sha256(np.asarray(pcm, dtype='<i2').tobytes()).hexdigest()
if digest != row['pcm_sha256'] or rate != 24000 or pcm.ndim != 1:
raise ValueError('Stored audio failed verification')
path = audio_directory / f"{row['original_id']}.wav"
if path.exists():
old, old_rate = sf.read(path, dtype='int16')
if old_rate != rate or not np.array_equal(old, pcm):
raise ValueError('Existing output WAV differs')
else:
sf.write(path, pcm, rate, format='WAV', subtype='PCM_16')
raw = {'schema_version': 1, 'kind': 'raw_alignment', 'episode_id': row['id'],
'audio': path.relative_to(output).as_posix(), 'text': row['text'],
'source': row['source'], 'source_url': 'https://www.openslr.org/141/',
'source_split': row['source_split'], 'speaker_id': row['speaker_id'],
'original_id': row['original_id'], 'split': split, 'license': row['license'],
'sample_rate': rate, 'valid_samples': len(pcm), 'duration_seconds': len(pcm) / rate,
'channels': 1, 'sample_width': 2,
'source_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'original_wav_sha256': row['source_audio_sha256'], 'pcm_sha256': digest,
'provenance': {'transformation': 'lossless release FLAC decoded to PCM16 WAV',
'release': 'nano-duplex-data-v1', 'archive_verified': True}}
target.write(json.dumps(raw, ensure_ascii=False, allow_nan=False) + '\n')
count += 1
if limit is not None and count >= limit:
break
if limit is not None and count >= limit:
break
if limit is not None and count >= limit:
break
temporary.replace(manifest)
return {'manifest': str(manifest), 'rows': count}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--snapshot', required=True)
parser.add_argument('--output', required=True)
parser.add_argument('--split', choices=['train', 'validation', 'test'], default='train')
parser.add_argument('--limit', type=int)
args = parser.parse_args()
print(json.dumps(materialize(args.snapshot, args.output, args.split, args.limit)))
|